May 10, 2012

Handle Save, Save & close and unload of CRM form

This is a tricky situation one can come across in CRM 4.0 development. Leaving the form can happen in three ways. Those are SAVE, SAVE AND CLOSE, UNLOAD
We can write JavaScript for all three occasions.


If you put below code in onLoad event, you can execute a script on unload.

// Put this in onload
window.onbeforeunload = function()
    alert("unload event")      


Saving is straight forward in CRM form, but you can distinguish two ways of saving by event mode. Try below script in save event.

var _mode = event.Mode;
alert("Save event .. with mode : " +_mode);

Different modes could be easily distinguished as blow.

SAVE - 1

Now my real focus is to do something when we leave a form with any of above three methods. Best example would be Quote entity can have total fields which depend on quotedetail entities under it (quotedetai is a child of quote). If we need them to be accurate at any given moment... we might need to do the calculations (unless we do it in plug-ins) whenever any of above events occur.

Way above event occurs are quite messy.
Please check what I found. Different combination of events trigger depends on circumstance.

SAVE (without change to form data) - Save event
SAVE (with change to form data) - save event, unload event
SAVE AND CLOSE (without change to form data) - save event, unload event

SAVE AND CLOSE (with change to form data) - save event, unload event

So, if we place the calculation event in all the three events, nothing will go wrong but in some occasions, it will run twice. Still I don’t know how to solve this simply. What we could do is maintaining a hidden check box (Boolean field) to say whether form needs recalculation. We should be smart enough to update this field even when child records are changed, if they influence the calculations.

Then we can add our own calculation methods to all three events, but calculation should always check the Boolean field before execution. In this way, we can avoid happening of calculation twice for no reason.

I am glad to hear if someone got better approach for this.

No comments:

Post a Comment