Thursday, May 30, 2019

Handling Record Changes using LDS (force:recordData)

Now we know how to perform CRUD opeartion using force:recordData.

Today we will be going to see how to handle changes on record using recordUpdated.

Sample syntax:

<force:recordData aura:id="forceRecordDataCmp"
    recordId="{!v.recordId}"
    layoutType="{!v.layout}"
    targetRecord="{!v.recordObject}"
    targetFields="{!v.recordFieldstoQuery}"
    targetError="{!v.recordError}"

    recordUpdated="{!c.recordUpdated}" />

For every force:recordData component referencing the updated record, LDS does two things.


  • LDS notifies all other instances of force:recordData of the change by firing the recordUpdated event with the appropriate changeType and changedFields value.
  • It sets the targetRecord and targetFields attribute on each force:recordData to the new record value. If targetRecord or targetFields is referenced by any UI, this automatically triggers a rerender so that the UI displays the latest data.

Note: If force:recordData is in EDIT mode, targetRecord and targetFields are not automatically updated.


Sample handler:

({
    recordUpdated: function(component, event, helper) {
        var eventParams = event.getParams();
        if(eventParams.changeType === "CHANGED") {
            // getting the fields that are changed for this record
            var changedFields = eventParams.changedFields;
           Alert('Fields change detected on: ' + JSON.stringify(changedFields));
            // Refereshing the component after change
            var resultsToast = $A.get("e.force:showToast");
            resultsToast.setParams({
                "title": "Saved",
                "message": "Record updatesd."
            });
            resultsToast.fire();
        } else if(eventParams.changeType === "LOADED") {
            Alert("Record is loaded successfully.");
        } else if(eventParams.changeType === "REMOVED") {
            var resultsToast = $A.get("e.force:showToast");
            resultsToast.setParams({
                "title": "Deleted",
                "message": "Record deleted."
            });
            resultsToast.fire();
        } else if(eventParams.changeType === "ERROR") {
            alert("Error: '"+ component.get("v.recordError"));
        }
    }
})

No comments:

Post a Comment