Sunday, January 18, 2009

CRM 4.0 - OnChange Firing after OnSave

While writing JavaScript customizations in CRM 4.0, I always assumed that onSave is the last event to occur before data saves to the database. However, I found a special cases where onChange gets fired after onSave. The scenario is when you are updating an entity such as account and the primary contact lookup field has a value. You blank out the lookup field and click save. The onChange event of primary contact fires after onSave. This was especially problematic if you have code in the onChange that blanks out fields on the form. The fields will save to the database blanked-out.

To get around this, I recommend adding code to any onChange event to prevent it from running after onSave.

OnLoad - Declare a public variable
document.IsSaving= false;

OnSave - Update the public variable
document.IsSaving= true;

OnChange - Exit out if the OnSave has Already Ran
if(document.IsSaving)
return;

// Some other logic