Skip to content

Commit

Permalink
Fixed page builder not redirecting to content edit on save
Browse files Browse the repository at this point in the history
  • Loading branch information
clevyr-anthony committed Aug 11, 2023
1 parent f015e5d commit 866378a
Show file tree
Hide file tree
Showing 3 changed files with 161 additions and 87 deletions.
8 changes: 3 additions & 5 deletions src/app/Http/Controllers/Admin/PageBuilderCrudController.php
Original file line number Diff line number Diff line change
Expand Up @@ -200,15 +200,13 @@ protected function setupUpdateOperation()
->allows_null(false)
->tab('Page Settings');

// $this->crud->removeAllSaveActions() uses the wrong method and is bugged
$this->crud->setOperationSetting('save_actions', []);
$this->crud->removeAllSaveActions();
// $this->crud->setOperationSetting('save_actions', []);

// Save Actions
$this->crud->addSaveAction([
'name' => 'save_and_edit_content',
'redirect' => function($crud, $request, $itemId) {
return backpack_url('pages/' . $itemId . '/edit#page-content');
},
'redirect' => fn($crud, $request, $itemId) => backpack_url('pages/' . $itemId . '/edit#page-content'),
'button_text' => 'Save and Edit Content',
'order' => 0,
]);
Expand Down
238 changes: 157 additions & 81 deletions src/resources/views/crud/form/form_content.blade.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,31 +2,32 @@

{{-- See if we're using tabs --}}
@if ($crud->tabsEnabled() && count($crud->getTabs()))
@include('pagebuilder::crud.form.show_tabbed_fields')
<input type="hidden" name="current_tab" value="{{ Str::slug($crud->getTabs()[0]) }}" />
@include('pagebuilder::crud.form.show_tabbed_fields')
<input type="hidden" name="_current_tab" value="{{ Str::slug($crud->getTabs()[0]) }}" />
@else
<div class="card">
<div class="card-body row">
@include('crud::inc.show_fields', ['fields' => $crud->fields()])
</div>
</div>
@endif


{{-- Define blade stacks so css and js can be pushed from the fields to these sections. --}}

@section('after_styles')
<link rel="stylesheet" href="{{ asset('packages/backpack/crud/css/crud.css') }}">
<link rel="stylesheet" href="{{ asset('packages/backpack/crud/css/form.css') }}">
<link rel="stylesheet" href="{{ asset('packages/backpack/crud/css/'.$action.'.css') }}">

<!-- CRUD FORM CONTENT - crud_fields_styles stack -->
@stack('crud_fields_styles')
{{-- CRUD FORM CONTENT - crud_fields_styles stack --}}
@stack('crud_fields_styles')

@endsection

@section('after_scripts')
<script src="{{ asset('packages/backpack/crud/js/crud.js') }}"></script>
<script src="{{ asset('packages/backpack/crud/js/form.js') }}"></script>
<script src="{{ asset('packages/backpack/crud/js/'.$action.'.js') }}"></script>

<!-- CRUD FORM CONTENT - crud_fields_scripts stack -->
@stack('crud_fields_scripts')
{{-- CRUD FORM CONTENT - crud_fields_scripts stack --}}
@stack('crud_fields_scripts')

<script>
<script>
function initializeFieldsWithJavascript(container) {
var selector;
if (container instanceof jQuery) {
Expand All @@ -47,111 +48,186 @@ function initializeFieldsWithJavascript(container) {
});
}
/**
* Auto-discover first focusable input
* @param {jQuery} form
* @return {jQuery}
*/
function getFirstFocusableField(form) {
return form.find('input, select, textarea, button')
.not('.close')
.not('[disabled]')
.filter(':visible:first');
}
/**
*
* @param {jQuery} firstField
*/
function triggerFocusOnFirstInputField(firstField) {
if (firstField.hasClass('select2-hidden-accessible')) {
return handleFocusOnSelect2Field(firstField);
}
firstField.trigger('focus');
}
/**
* 1- Make sure no other select2 input is open in other field to focus on the right one
* 2- Check until select2 is initialized
* 3- Open select2
*
* @param {jQuery} firstField
*/
function handleFocusOnSelect2Field(firstField){
firstField.select2('focus');
}
/*
* Hacky fix for a bug in select2 with jQuery 3.6.0's new nested-focus "protection"
* see: https://github.com/select2/select2/issues/5993
* see: https://github.com/jquery/jquery/issues/4382
*
*/
$(document).on('select2:open', () => {
setTimeout(() => document.querySelector('.select2-container--open .select2-search__field').focus(), 100);
});
jQuery('document').ready(function($){
// trigger the javascript for all fields that have their js defined in a separate method
initializeFieldsWithJavascript('form');
// Retrieves the current form data
function getFormData() {
return new URLSearchParams(new FormData(document.querySelector("main form"))).toString();
}
// Prevents unloading of page if form data was changed
function preventUnload(event) {
if (initData !== getFormData()) {
// Cancel the event as stated by the standard.
event.preventDefault();
// Older browsers supported custom message
event.returnValue = '';
}
}
@if($crud->getOperationSetting('warnBeforeLeaving'))
const initData = getFormData();
window.addEventListener('beforeunload', preventUnload);
@endif
// Save button has multiple actions: save and exit, save and edit, save and new
var saveActions = $('#saveActions'),
crudForm = saveActions.parents('form'),
saveActionField = $('[name="save_action"]');
saveActions.on('click', '.dropdown-menu a', function(){
var saveAction = $(this).data('value');
saveActionField.val( saveAction );
crudForm.submit();
});
var saveActions = $('#saveActions')
crudForm = saveActions.parents('form')
// Ctrl+S and Cmd+S trigger Save button click
$(document).keydown(function(e) {
if ((e.which == '115' || e.which == '83' ) && (e.ctrlKey || e.metaKey))
{
e.preventDefault();
$("button[type=submit]").trigger('click');
return false;
}
return true;
if ((e.which == '115' || e.which == '83' ) && (e.ctrlKey || e.metaKey))
{
e.preventDefault();
$("button[type=submit]").trigger('click');
return false;
}
return true;
});
// prevent duplicate entries on double-clicking the submit form
crudForm.submit(function (event) {
window.removeEventListener('beforeunload', preventUnload);
$("button[type=submit]").prop('disabled', true);
});
// Place the focus on the first element in the form
@if( $crud->getAutoFocusOnFirstField() )
@php
$focusField = Arr::first($fields, function($field) {
return isset($field['auto_focus']) && $field['auto_focus'] == true;
});
@endphp
let focusField;
@if ($focusField)
@php
$focusField = Arr::first($fields, function($field) {
return isset($field['auto_focus']) && $field['auto_focus'] == true;
});
$focusFieldName = isset($focusField['value']) && is_iterable($focusField['value']) ? $focusField['name'] . '[]' : $focusField['name'];
@endphp
focusField = $('[name="{{ $focusFieldName }}"]').eq(0);
@else
focusField = getFirstFocusableField($('form'));
@endif
@if ($focusField)
@php
$focusFieldName = isset($focusField['value']) && is_iterable($focusField['value']) ? $focusField['name'] . '[]' : $focusField['name'];
@endphp
window.focusField = $('[name="{{ $focusFieldName }}"]').eq(0),
@else
var focusField = $('form').find('input, textarea, select').not('[type="hidden"]').eq(0),
@endif
fieldOffset = focusField.offset().top,
scrollTolerance = $(window).height() / 2;
const fieldOffset = focusField.offset().top;
const scrollTolerance = $(window).height() / 2;
focusField.trigger('focus');
triggerFocusOnFirstInputField(focusField);
if( fieldOffset > scrollTolerance ){
$('html, body').animate({scrollTop: (fieldOffset - 30)});
}
if( fieldOffset > scrollTolerance ){
$('html, body').animate({scrollTop: (fieldOffset - 30)});
}
@endif
// Add inline errors to the DOM
@if ($crud->inlineErrorsEnabled() && $errors->any())
window.errors = {!! json_encode($errors->messages()) !!};
// console.error(window.errors);
$.each(errors, function(property, messages){
var normalizedProperty = property.split('.').map(function(item, index){
return index === 0 ? item : '['+item+']';
}).join('');
@if ($crud->inlineErrorsEnabled() && session()->get('errors'))
window.errors = {!! json_encode(session()->get('errors')->getBags()) !!};
$.each(errors, function(bag, errorMessages){
$.each(errorMessages, function (inputName, messages) {
var normalizedProperty = inputName.split('.').map(function(item, index){
return index === 0 ? item : '['+item+']';
}).join('');
var field = $('[name="' + normalizedProperty + '[]"]').length ?
$('[name="' + normalizedProperty + '[]"]') :
$('[name="' + normalizedProperty + '"]'),
container = field.closest('.form-group');
// iterate the inputs to add invalid classes to fields and red text to the field container.
container.find('input, textarea, select').each(function() {
let containerField = $(this);
// add the invalid class to the field.
containerField.addClass('is-invalid');
// get field container
let container = containerField.closest('.form-group');
// TODO: `repeatable-group` should be deprecated in future version as a BC in favor of a more generic class `no-error-display`
if(!container.hasClass('repeatable-group') && !container.hasClass('no-error-display')){
container.addClass('text-danger');
}
});
var field = $('[name="' + normalizedProperty + '[]"]').length ?
$('[name="' + normalizedProperty + '[]"]') :
$('[name="' + normalizedProperty + '"]'),
container = field.parents('.form-group');
$.each(messages, function(key, msg){
// highlight the input that errored
var row = $('<div class="invalid-feedback d-block">' + msg + '</div>');
container.addClass('text-danger');
container.children('input, textarea, select').addClass('is-invalid');
// TODO: `repeatable-group` should be deprecated in future version as a BC in favor of a more generic class `no-error-display`
if(!container.hasClass('repeatable-group') && !container.hasClass('no-error-display')){
row.appendTo(container);
}
$.each(messages, function(key, msg){
// highlight the input that errored
var row = $('<div class="invalid-feedback">' + msg + '</div>');
row.appendTo(container);
// highlight its parent tab
@if ($crud->tabsEnabled())
var tab_id = $(container).closest('[role="tabpanel"]').attr('id');
$("#form_tabs [aria-controls="+tab_id+"]").addClass('text-danger');
@endif
});
// highlight its parent tab
@if ($crud->tabsEnabled())
var tab_id = $(container).closest('[role="tabpanel"]').attr('id');
$("#form_tabs [aria-controls="+tab_id+"]").addClass('text-danger');
@endif
});
});
});
@endif
$("a[data-toggle='tab']").click(function(){
currentTabName = $(this).attr('tab_name');
$("input[name='current_tab']").val(currentTabName);
currentTabName = $(this).attr('tab_name');
$("input[name='_current_tab']").val(currentTabName);
});
if (window.location.hash) {
$("input[name='current_tab']").val(window.location.hash.substr(1));
$("input[name='_current_tab']").val(window.location.hash.substr(1));
}
});
</script>

});
</script>

@include('crud::inc.form_fields_script')
@include('crud::inc.form_fields_script')
@endsection
2 changes: 1 addition & 1 deletion src/resources/views/crud/pages/edit.blade.php
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,7 @@ class="form-control"
</div>

<p class="help-block">
Select the date you want this page to be published, pressing delete will remove it.
Select the date you want this page to be published, pressing <b>delete</b> will remove it.
</p>
</div>
</div>
Expand Down

0 comments on commit 866378a

Please sign in to comment.