Reputation: 3633
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?
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
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:
top.Mscrm
instead of just Mscrm
.Upvotes: 3