ConfirmEditNotSaved

Summary: Ask users to confirm if they are leaving the edit page without saving
Version: All
Prerequisites: Javascript enabled
Status:
Maintainer:
Categories:Editing

Questions answered by this recipe

How can I prevent editors from accidentally losing their edits?

If a page is edited and the user attempts to navigate away, a javascript pop-up will request a confirmation and give the user a second chance.

Description

Add the following code to your Local/Config.php file. Make sure there are no unneeded line breaks.

if ($action == 'edit') {

XLSDV('en', array(
  'e_sure' => 'You have attempted to leave this page.  If you have made any changes to the fields without clicking the Save button, your changes will be lost. Are you sure you want to exit this page?'
  ));
XLSDV('nl', array(
  'e_sure' => 'Je doet een poging deze pagina te verlaten, weet je dat zeker? De
 wijzigingen zijn nog niet opgeslagen!!'
  ));
SDV($InputTags['e_textarea'][':html'], 
    "<textarea \$InputFormArgs onkeydown='if (event.keyCode==27) event.returnValue=false;' ".
    "onchange='needToConfirm = true;'>".
    "\$EditText</textarea>"
    );
SDV($InputTags['e_saveeditbutton'][':html'],"<input type='submit' \$InputFormArgs onclick='needToConfirm = false;'>");
SDV($InputTags['e_previewbutton'][':html'],"<input type='submit' \$InputFormArgs onclick='needToConfirm = false;'>");
SDV($InputTags['e_cancelbutton'][':html'],"<input type='submit' \$InputFormArgs onclick='needToConfirm = false;'>");
SDV($InputTags['e_resetbutton'][':html'],"<input type='submit' \$InputFormArgs onclick='needToConfirm = false;'>");
SDV($InputTags['e_savebutton'][':html'],"<input type='submit' \$InputFormArgs onclick='needToConfirm = false;'>
<script language='JavaScript'>
  var needToConfirm = false;
  window.onbeforeunload = confirmExit;
  function confirmExit()
  {
    if (needToConfirm) return \"" . XL('e_sure') . "\";
  }
</script>
"
  );
}

Notes

Old comments and discoveries have been factored into the code for a more elegant solution.

See Also

Contributors

BrBrBr

Comments

See discussion at ConfirmEditNotSaved-Talk

User notes? : If you use, used or reviewed this recipe, you can add your name. These statistics appear in the Cookbook listings and will help newcomers browsing through the wiki.