Tuesday, May 20, 2014

MS CRM Simulating OnChange Javascript event for Owner field

You might get a surprise when you add the On Change event to an owner field - you will find that it doesn't fire.  The reason for this is that the when changing the owner of a record the form is actually saved.

Lucky for you, there is a way to achieve the same functionality as the On Change, and it's quite straight forward.

Save Mode = Assign

Basically, you can add a On Save event (making sure you tick the pass the context box when you set it up), and then you can find out what triggered the On Save event inspecting the SaveMode and finding out if it was triggered by an "Assign".

OwnerId Is Dirty Check

The only other thing you'll need to do is check also if the OwnerId field is dirty.  Why is this needed?  Well, imagine that you've got a required field that you haven't filled in and then you go to change the owner. As changing the Owner causes an On Save event, this also triggers validation and you'll get an error message indicating the field is required before it gets to your logic, and the Save won't actually occur.  This leaves the form in state where the OwnerId has actually been changed but your "OnChange" logic won't fire on the next save because the logic is looking for an Save Mode of "Assign" - which won't be raised again until someone attempts to re-assign the record.  So, the next best thing is to do a check to see if the OwnerId is dirty (which will only happen if the Save attempt failed validation when the owner is changed) and your on change logic can fire then.  Not perfect, but good enough in most situations.

So here's an example of some code that will do the job:

function Form_OnSave(context) {

    var saveMode_Assign = 47;

    if (context.getEventArgs().getSaveMode() == saveMode_Assign 
        || Obs.getAttribute("ownerid").getIsDirty()) {
        OwnerId_OnChange(); // Put your logic here!