Pages

Friday, June 14, 2013

Prompt user before leaving page if a form is dirty

Ext.application({

    init: function(){

        Ext.EventManager.addListener(window, 'beforeunload', this.onBeforeUnload, this, {
            normalized:false //we need this for firefox
        });    
    },

    onBeforeUnload: function(e){

        var showMessage = false;
        var MESSAGE = 'You have unsaved changes.';

        Ext.Array.each(Ext.ComponentQuery.query('form'), function (form) {
            if (form.isDirty()) {
                showMessage = true;
                return false; //exit the loop
            }
        });

        /* optionally notify the server when a user has unloaded the app:

         Ext.Ajax.request({
           url: 'log.php',
           method:'POST',
           async: false  //don't change
         });

        */

        if (showMessage === true) {
            if (e) e.returnValue = MESSAGE;
            if (window.event) window.event.returnValue = MESSAGE;
            return MESSAGE;
        }
});


You will probably also want to turn on trackResetOnLoad for your forms as well:



Ext.form.Basic.override({
  trackResetOnLoad:true
});


Ext.form.Panel.override({
  trackResetOnLoad:true
});