Dynamics 365 – Form OnSave Event

Advertisements
Advertisements

Within the context of Dynamics 365, the OnSave event represents a crucial trigger that enables developers to intervene in the save process. This feature provides an opportunity to implement custom business logic, enforce data validation, and proficiently manage the pre-save phase.

Implementing OnSave Event Handling

In Dynamics 365, you can incorporate a custom function to be called when the OnSave event is triggered using the following code example:

formContext.data.entity.addOnSave(myFunction);

By using this code, the myFunction is set up to handle the OnSave event, allowing you to run custom logic before the save operation.

Now let’s create an actual function to run during OnSave event. validateOpportunityScoreOnSave function performs validation checks on the opportunity score before the save operation is executed. This function ensures that the score aligns with predefined criteria or business rules, thereby maintaining data integrity and accuracy within the system.

function OnLoad(executionContext){
var formContext = executionContext.getFormContext();
//Register custom event
formContext.data.entity.addOnSave(validateOpportunityScore);
}
function validateOpportunityScoreOnSave(executionContext) {
var formContext = executionContext.getFormContext();
var opportunityScore = formContext.getAttribute("new_opportunityscore").getValue();
if (opportunityScore < 0 || opportunityScore > 100) {
formContext.getControl("new_opportunityscore").setNotification("Opportunity score must be between 0 and 100.");
//Prevent save
executionContext.getEventArgs().preventDefault();
} else {
formContext.getControl("new_opportunityscore").clearNotification();
}
}
view raw OnSave.js hosted with ❤ by GitHub

OnSave Event Occurs When

  • When the user clicks the Save or Refresh button in the command bar, even if there are no changes to be saved.
  • When the user leaves the form with unsaved data remaining.
  • Execution of the formContext.data.entity.save method, even when no data has been changed.
  • Execution of the formContext.data.save method when there’s unsaved data in the form.
  • Execution of the formContext.data.refresh method with a true value as the first parameter, and unsaved data in the form.
  • The AutoSave option, set to trigger 30 seconds after unsaved changes are detected in the form.

Related Posts

Advertisements
Advertisements
Advertisements

Leave a comment

Create a website or blog at WordPress.com