Tim Hutchison
Tim Hutchison

Reputation: 3633

Form Event OnSave not executing Promise

I have a web resource in Dynamics CRM where I am trying to add logic to execute on save. I am using the addOnSave() method to attach my logic to the save. When I use a Promise in my save logic, Save & Close exits the page before my save completes. How can I get my save logic to fully execute before the web resource is closed?

pseudocode

Xrm.Event.addOnSave(function () {
  // Code makes it here
  Promise.all([promises]).then(function(){
    // Code never makes it here
    secondPromise.then(function(){
      showAlert();
      setTimeout(function(){
        closeAlert();
      }, 5000);
    });
  });
});

Upvotes: 0

Views: 2768

Answers (1)

Polshgiant
Polshgiant

Reputation: 3664

You want to cancel the save and then reissue it, like this:

Xrm.Page.data.entity.addOnSave(function (context) {
  var eventArgs = context.getEventArgs();
  eventArgs.preventDefault(); // cancels the save (but other save handlers will still run)

  Promise.all([promises]).then(function(){
    // Code never makes it here
    secondPromise.then(function(){
      showAlert();
      setTimeout(function(){
        closeAlert();

        // reissue the save
        Xrm.Page.data.entity.save('saveandclose');
      }, 5000);
    });
  });
});

In response to your comment about the bug where preventDefault doesn't properly stop a Save and Close event: use the Ribbon Workbench from the XrmToolbox to override the Save and Close button to point to a custom function which might look something like this:

function customSaveAndClose() {
  if (customSaveIsNeeded) {
    // execute your custom code
  } else {
    Xrm.Page.data.entity.save('saveandclose');
  }
}

You can for sure override the S&C button at the Application Ribbon level which would override it for all entities, but I believe you can override it for just one entity at a time as well.

If you don't want to mess with editing the ribbon (it's a little intimidating if you've never done it before) and if you don't have strict requirements regarding unsupported customizations, you can also take the easier route of simply overriding the Mscrm.RibbonActions.saveAndCloseForm function which is what the native S&C buttons call. That would look something like this:

// defined in /_static/_common/scripts/RibbonActions.js
Mscrm.RibbonActions.saveAndCloseForm = function() {
   // your code here
}

Some things to note about this approach:

  • It's not supported and could break with any update
  • CRM forms consist of multiple frames, so if you define that function in your custom script and it doesn't get executed, change your definition to top.Mscrm instead of just Mscrm.
  • If you have to support mobile clients, you should probably avoid this approach and override the ribbon button instead.

Upvotes: 3

Related Questions