CRM 2013 brings with it the feature of auto-saving forms after new data in entered. While this is helpful to users, it does mean that we have to be a wee bit careful with our JavaScript coding (and plugins for that matter, but we’ll cover that in a separate blog).

The places where this change is immediately obvious are the onLoad and onSave events on a form. There is often a business scenario where you are required to have a piece of logic trigger when the form is initially loaded. However, given that the form quietly reloads behind the scenes every time the auto-save fires, you can end up executing this logic multiple times as the form continues to auto-save and reload while the user is on it.

Below I will outline how to work your javascript around the form auto-save event using a simply method which alerts the user when the form is loaded or saved;

CRM 2011 – onLoad
function alertOnLoad() {
    alert(
"The form has been loaded.");
}

CRM 2013 – onLoad
var FORMLOADED = false;

function
alertOnLoad() {
   
if (!FORMLOADED) {
        alert(
"The form has been loaded.");
    }
    FORMLOADED =
true;
}

The above method will ensure that the code will only get triggered the first time the form is loaded. This allows flexibility where if you want an onLoad event to trigger eve after auto-saves you can simply not put the check around it.

The auto-save events do not clear global variables, which makes this a viable method to ensure that onLoad events are only fired once.

CRM 2011 – onSave
function alertOnSave(eventArgs) {
    alert(
"The form has been saved.");
}

CRM 2013 – onSave
function alertOnSave(eventArgs) {
   
var saveType = eventArgs.getEventArgs().getSaveMode();
   
if (saveType == 70) { //AutoSave
        Xrm.Page.data.setFormDirty(
true);
    }
   
else {
        alert(
"The form has been saved.");
    }
}

The above method for handling save events on auto-save is a wee bit more complicated. Every time the auto-save event is triggered, we need to ensure that logic we want to only get called only when a traditional save event happens can happily ignore these auto-saves. Simply doing a check on getSaveMode will quickly tell you whether you want to run your onSave event or not, but we must account for the fact that the auto-saves are saving data, which could allow people to not have the do a traditional save to the form before navigating elsewhere in the system.

setFormDirty is a simple work-around for this which will mean that the final save event is always triggered if any data on the form has been changed (as the auto-saves only kick in when data has been changed).

I’m sure as time goes on we’ll find creative ways to play about with the form auto-saves, so check back here often for blogs on this and other new javascript features coming with CRM 2013, along with plenty of other posts on other CRM 2013 areas!