Blog, Development

Cancelling save event based on the result of async operation

This post is similar to previous one related to showing/hiding of the button based on the result of async operation but in this scenario script allows/disallows form to be saved. In my case I check if there is any account with the same “Account Number” available already and if there is script blocks the save. Yes, I know that it’s safer to allow platform to that task for me (for example using Alternate Key feature or so) but it’s just an example that demonstrates the approach could be used in similar use cases.

So here is the code with detailed comments what is happening:

Don’t forget to set “Pass execution context as first parameter” checkbox during the registration of handler:

If you attach onsave handlers on-the-fly inside onload handler using addOnSave method executionContext is passed inside automatically as a first parameter.

PS I appreciate Chris Groh for code review and suggestions related to:

  • different save modes
  • sequential execution of several save handlers


  1. Great article Andrew! And the previous one also.
    In order to do same thing, I used Promise. With your code, it seems easier.

    Thanks for sharing

  2. Hi Andrew,
    Thanks for your article.
    We’ve used the same approach for some time.
    But if you need ot save something on the form calling
    ctx.getFormContext() => {
    then -> will always get a canceled callback.
    of course, there’s a workaroud but it should be kept in mind.

    1. Sergii,
      You are welcome. There always will be a scenario that is not covered by the code provided. That’s why we are paid – to close those gaps.

  3. execContext.getEventArgs().preventDefault(); is not working in CRM online. It is not throwing error also. Tried debugging javascript. But getEventArgs() is not null. When I print it, it is set to an object. Also Passexecutionparameter is checked in Handler properties. isDefaultPrevented also returns the correct value but preventdefault is not working.

    Any suggestions !!!


    1. Neha,
      I’m not sure why it doesn’t work for you. I did my development in online environment and it worked fine for me.

  4. Hi, should this script be attached to the OnSave event of the form? or is it better to attach it to the OnLoad event? Thanks

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.