![]() |
|
Snippets |
|
This JavaScript code registers a change detection mechanism in every form field and notifies the user about unsaved changes. No changes need to be applied to existing modules/actions. Additionaly, the TinyMCE helper can be changed in order to detect changes there as well.
Only requirement: the links for leaving the page need to be in a container with id "header". This can of course be changed.
Add this to the head of the page (or to an external js-file):
var changesDetected = false; /** * Registers a change detection mechanism that notifies users about unsaved changes whenever they click on a link. */ function registerChangeDetection() { /** * Notifies user about unsaved changes */ function notifyAboutChanges(e) { if(changesDetected){ //My choice: modal dialog using modalbox (http://www.wildbit.com/labs/modalbox/) //Modalbox.show('<div class=\'warning\'><p>Before continuing, you need to save you changes.</p> <input type=\'button\' value=\'Ignore changes\' onclick=\'changesDetected=false;Modalbox.hide()\' style=\'color: #999\' /> <input type=\'button\' value=\'OK\' onclick=\'Modalbox.hide()\' /></div>', {title: 'Warning', width: 300}); //Alternative: alert('Before continuing, you need to save your changes.'); return false; } } /* Add change detection to every form field */ if(document.forms.sf_admin_edit_form != null) { var elements = Form.getElements(document.forms.sf_admin_edit_form); elements.each(function(item) { item.onchange = function(e) { changesDetected = true; } }); } /* Add an onclick handler to every link in the container with id "header" */ var links = $$('#header a'); links.each(function(item) { if(!(item.onclick instanceof Function)) { //Avoid overwriting existing onclick handlers item.onclick = notifyAboutChanges; } }); }
Register the change detection in the body tag:
<body onload="registerChangeDetection()">
I also modified the sfRichTextEditorTinyMCE helper in order to use TinyMCE 3 (currently beta). Here is the code relevant to change detection to be put into TinyMCE.init({...}) (Go to http://wiki.moxiecode.com/index.php/TinyMCE:API/tinymce.Editor/onChange for more information):
setup: function(ed) { var i = 0; ed.onChange.add(function(ed, l) { if(i == 0) i++ //Ignore the first change else changesDetected = true; }); }