Automating Field Synchronization in Dynamics 365: Updating Child Records on Form Save

 

Automating Field Synchronization in Dynamics 365: Updating Child Records on Form Save

Introduction

In Dynamics 365, maintaining data integrity and consistency across related records is a common requirement. One practical scenario is when specific field changes in a parent entity should reflect in its child entities. This article focuses on a case involving the tri_programsession entity and its related appointment records. We demonstrate how to automate the process of updating child records based on changes in the parent form, utilizing Dynamics 365's JavaScript API.

Understanding getIsDirty()

A key component of our implementation is the getIsDirty() method. This method is part of Dynamics 365's JavaScript API and is used to determine if an attribute (field) has been modified since it was last saved. If a field has been changed, getIsDirty() returns true; otherwise, it returns false. This method allows us to efficiently check if specific fields of interest have been modified, triggering the update process only when necessary.

Scenario Overview

In our scenario, we want to update certain fields in all child appointment records when either tri_locationid, tri_schedulestartdateandtime, or tri_scheduleenddateandtime fields in the tri_programsession entity are modified and the record is saved.

Technical Implementation

JavaScript Code

Here is the JavaScript code that can be attached to the tri_programsession entity's form. This code will execute during the form's save event, updating the child appointment records as needed.


// This function is triggered on the form's save event.
function updateRelatedAppointmentsOnSave(executionContext) {
    var formContext = executionContext.getFormContext();

    // Checking if the specified fields are modified using getIsDirty().
    var locationField = formContext.getAttribute("tri_locationid");
    var startDateField = formContext.getAttribute("tri_schedulestartdateandtime");
    var endDateField = formContext.getAttribute("tri_scheduleenddateandtime");

    if (!locationField.getIsDirty() && !startDateField.getIsDirty() && !endDateField.getIsDirty()) {
        // Exit if none of the specified fields are changed.
        return;
    }

    // Retrieving the values from the modified fields.
    var programSessionId = formContext.data.entity.getId();
    var locationId = locationField.getValue();
    var scheduleStart = startDateField.getValue();
    var scheduleEnd = endDateField.getValue();
    var locationName = locationId ? locationId[0].name : "";

    // Forming the query to retrieve related appointment records.
    var query = "?$filter=_tri_programsessionid_value eq " + programSessionId.replace(/[{}]/g, ""); // Remove curly braces

    // API call to retrieve and update the related appointment records.
    Xrm.WebApi.retrieveMultipleRecords("appointment", query).then(
        function (result) {
            result.entities.forEach(function (appointment) {
                var updateEntity = {
                    "location": locationName,
                    "scheduledstart": scheduleStart,
                    "scheduledend": scheduleEnd
                };

                Xrm.WebApi.updateRecord("appointment", appointment.appointmentid, updateEntity).then(
                    function success(result) {
                        console.log("Appointment updated: " + result.id);
                    },
                    function (error) {
                        console.error("Error updating appointment: " + error.message);
                    }
                );
            });
        },
        function (error) {
            console.error("Error retrieving appointments: " + error.message);
        }
    );
}


Explanation of the Code

  1. Function Definition: The updateRelatedAppointmentsOnSave function is bound to the form's save event.
  2. Dirty Check: It uses getIsDirty() to check if tri_locationid, tri_schedulestartdateandtime, or tri_scheduleenddateandtime have been modified.
  3. Retrieving and Updating: Retrieves new values of modified fields, fetches child appointment records, and updates them accordingly.
  4. Error Handling: Includes logging for successful updates and error reporting.

Deploying the Code

  1. Add as a Web Resource: Add this JavaScript to a web resource in Dynamics 365.
  2. Bind to OnSave Event: Attach the function to the OnSave event of the tri_programsession form.
  3. Testing: Verify the functionality by modifying the specified fields and saving the form.

Conclusion

This automated approach enhances data consistency in Dynamics 365. By utilizing the getIsDirty() method, we ensure that only necessary updates are made, improving system performance and maintaining data integrity across related records.

No comments:

Post a Comment