Before I go ahead and explain, let me accept this. I was not aware of the newly introduced client APIs in Model driven apps. And this one was pure serendipity.
You might be thinking – Isn’t there formContext.data.save().then(successCallback, errorCallback) function which allow us to do that?
Yes it does. But I am not talking about that. Infact the above construct does not take care of all situations. So if you are looking to achieve the below requirements and explore a new API, continue reading.
- Register Post Save event handler when you use the OOB save button on Model driven app form.
- Register Post Save event handler when you save a record using formContext.data.entity.save() from your form script or web resource.
While PowerApps and Power Automate have hogged the limelight and low code/ no code is the mantra of the day, it’s undeniable that more often than not we need to fall back to client side API for requirements.
And slowly but silently, with every release Microsoft is adding more and more operations to its repertoire. One such event is the new PostSave event. You heard it right. Now you can add event handlers once save is completed.
Without further delay, let’s see some code in action. To start with, below is sample code.
function onLoad(eContext) {
var formContext = eContext.getFormContext();
formContext.data.entity.addOnPostSave(onPostSave);
}
function onPostSave(eContext) {
debugger;
var saveEventArgs = eContext.getEventArgs();
if (!saveEventArgs.getIsSaveSuccess()) {
var saveError = saveEventArgs.getSaveErrorInfo();
}
}
I registered the onLoad function on form onload event. In onload function, I am using the new introduced addOnPostSave() function to add an event handler for save complete event. Below is the new stuff in action.
Observe carefully. When I click on Save button, the form saves and then it fires the event registered on post save. Also notice couple of new functions
- getIsSaveSuccess() – Indicates whether the save event is success or not.
- getSaveError() – If any error have happened during save, it will give you the error.
The registered function will fire whenever you are trying to save the form. Be it on click of the ‘Save’ button on the form. Or save the form dynamically using formContext.data.entity.save(). Or using parent.Xrm.Page.data.entity.save() from a webresource embedded on the form.
Wonderful isn’t it? Hope this helped!
Debajit Dutta
Business Solutions MVP
Discover more from Debajit's Power Apps & Dynamics 365 Blog
Subscribe to get the latest posts sent to your email.