Skip to content

Commit

Permalink
Merge pull request #5560 from Laravel-Backpack/fix-warn-before-leaving
Browse files Browse the repository at this point in the history
fix warn before leaving - remove backpack dynamic inputs from serialization
  • Loading branch information
pxpm authored Jul 15, 2024
2 parents facb579 + df02e1f commit 67cc080
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 4 deletions.
4 changes: 3 additions & 1 deletion src/config/backpack/operations/create.php
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,9 @@
// Should we show a cancel button to the user?
'showCancelButton' => true,

// Should we warn a user before leaving the page with unsaved changes?
// Should we warn the user before leaving the page with unsaved changes?
// NOTE: this works by removing all fields from the form data serialization where field name starts with "_" (underscore). Usualy backpack internal attributes.
// if you have fields that start with an underscore, you need to change the field name, or this functionality wont detect changes in that field.
'warnBeforeLeaving' => false,

// Before saving the entry, how would you like the request to be stripped?
Expand Down
14 changes: 11 additions & 3 deletions src/resources/views/crud/form_content.blade.php
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,15 @@ function handleFocusOnSelect2Field(firstField){
// Retrieves the current form data
function getFormData() {
return new URLSearchParams(new FormData(document.querySelector("main form"))).toString();
let formData = new FormData(document.querySelector("main form"));
// remove internal inputs from formData, the ones that start with "_", like _token, _http_referrer, etc.
let pairs = [...formData].map(pair => pair[0]);
for (let pair of pairs) {
if (pair.startsWith('_')) {
formData.delete(pair);
}
}
return new URLSearchParams(formData).toString();
}
// Prevents unloading of page if form data was changed
Expand All @@ -114,8 +122,8 @@ function preventUnload(event) {
}
@if($crud->getOperationSetting('warnBeforeLeaving'))
const initData = getFormData();
window.addEventListener('beforeunload', preventUnload);
const initData = getFormData();
window.addEventListener('beforeunload', preventUnload);
@endif
// Save button has multiple actions: save and exit, save and edit, save and new
Expand Down

0 comments on commit 67cc080

Please sign in to comment.