Validating Data with Alerts in Dynamics 365 onSave Event

 

Validating Data with Alerts in Dynamics 365 onSave Event

Introduction

This article presents a straightforward method to validate data in Microsoft Dynamics 365 using JavaScript. Specifically, it demonstrates how to validate a specific column value before saving a record and alerting the user if certain conditions are not met.

Scenario

Consider a case where a record in Dynamics 365 must meet a unique condition before being saved. For example, ensuring that only one 'Task' in a 'Project' is marked as 'High Priority'.

Solution

The solution involves using the onSave event to:

  1. Prevent the default save operation.
  2. Perform an asynchronous check for the condition.
  3. Alert the user and halt the save if the condition is violated.

Sample Code

Here's a sample JavaScript function to implement this:

function validatePriorityOnSave(executionContext)
{
    var eventContext = executionContext.getEventArgs();
    var formContext = executionContext.getFormContext();
    var priority = formContext.getAttribute("task_priority").getValue();
    var projectId = formContext.getAttribute("project_id").getValue();

    if(priority === 100000000 && projectId) // Assuming 100000000 is 'High Priority'
    {
        eventContext.preventDefault();

        Xrm.WebApi.retrieveMultipleRecords("Task", "?$filter=task_priority eq 100000000 and _project_id_value eq " + projectId[0].id).then(
            function (results)
            {
                if(results.entities.length > 0)
                {
                    Xrm.Navigation.openAlertDialog({ text: "Each Project can only have one Task with 'High Priority'.\nThere is already an existing Task with this priority." });
                }
                else
                {
                    formContext.data.save();
                }
            },
            function (error)
            {
                console.error("Error in validation: " + error.message);
            }
        );
    }
}


Conclusion

This approach ensures that users are alerted about specific data validation rules, enhancing data integrity and enforcing business logic in Dynamics 365 forms.


No comments:

Post a Comment