Lightning Data Service Basics: Handle Record Changes and Errors
accEdit Component Code
<aura:component implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId" access="global" >
<aura:attribute name="record" type="Object"
description="The record object to be displayed"/>
<aura:attribute name="simpleRecord" type="Object"
description="A simplified view record object to be displayed"/>
<aura:attribute name="recordSaveError" type="String"
description="An error message bound to force:recordData"/>
<force:recordData aura:id="accountRecord"
layoutType="FULL"
recordId="{!v.recordId}"
targetError="{!v.recordSaveError}"
targetRecord="{!v.record}"
targetFields="{!v.simpleRecord}"
recordUpdated="{!c.recordUpdated}"
fields="Name"
mode="EDIT"/>
<!-- Display an editing form -->
<div class="Record Details">
<lightning:card iconName="action:edit" title="Edit Account">
<div class="slds-p-horizontal--small">
<lightning:input label="Account Name" value="{!v.accountRecord.Name}"/>
<br/>
<lightning:button label="Save Account" variant="brand" onclick="{!c.handleSaveRecord}" />
</div>
</lightning:card>
</div>
<!-- Display Lightning Data Service errors, if any -->
<aura:if isTrue="{!v.recordSaveError}">
<div class="recordError">
{!v.recordSaveError}</div>
</aura:if>
</aura:component>
accEdit Controller Component
({
recordUpdated: function(component, event, helper) {
var eventParams = event.getParams();
if(eventParams.changeType === "CHANGED") {
// get the fields that are changed for this record
var changedFields = eventParams.changedFields;
//console.log('Fields that are changed: ' + JSON.stringify(changedFields));
// record is changed so refresh the component (or other component logic)
var resultsToast = $A.get("e.force:showToast");
resultsToast.setParams({
"title": "Saved",
"message": "The record was updated."
});
resultsToast.fire();
} else if(eventParams.changeType === "LOADED") {
} else if(eventParams.changeType === "REMOVED") {
} else if(eventParams.changeType === "ERROR") {
}
},
handleSaveRecord: function(cmp, event, helper) {
cmp.find("accountRecord").saveRecord($A.getCallback(function(saveResult) {
if (saveResult.state === "ERROR") {
var errMsg = "";
for (var i = 0; i < saveResult.error.length; i++) {
errMsg += saveResult.error[i].message + "\n";
}
cmp.set("v.recordSaveError", errMsg);
} else {
cmp.set("v.recordSaveError", "");
}
}));}
})
Note:If you keep getting this error "The 'accEdit' Lightning Component JS Controller does not appear to be setting 'v.recordSaveError' with an error message" then make sure in handleSaveRecord function you are using "cmp" not any other name.