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

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.


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!!'
    "<textarea \$InputFormArgs onkeydown='if (event.keyCode==27) event.returnValue=false;' ".
    "onchange='needToConfirm = true;'>".
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') . "\";


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

See Also




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.