Use Lightning Data Service – No To Apex Controller In Lightning Components
Like Standard Controllers in Visualforce, Salesforce has provided one of the exciting features in Summer 17 is Lightning Data Service.
We can retrieve a record data without writing a single piece of Apex Server side code. We need to use the new force:recordData component to achieve this.
Let’s understand how to use force:recordData
Loading a Record:
To load a record using lightning data service ( force:recordData ), we need specify the following:
- The ID of the record to load
- Which component attribute to assign the loaded record
- A list of fields to load
Syntax:
1 2 3 4 5 6 7 8 9 10 11 | <force:recordData aura:id="recordLoader" recordId="{!v.recordId}" layoutType="FULL" targetRecord="{!v.record}" targetFields="{!v.simpleRecord}" targetError="{!v.recordError}" recordUpdated="{!c.handleRecordUpdated}" /> |
where,
- recordId – the id of the record to load.
- layoutType –
FULL – PageLayout of the record ( If there are multiple page layouts for different record types, the pagelayout of the recordid will be taken)
MINI – Compact Layout - targetRecord – where to store the result
- targetFields – A simplified view of the fields in targetRecord. We generally use this object to refer the fields in our markup
- targetError – If any error is encountered, it stores the error message.
- fields – Specifies which of the record’s fields to query.
Either fields or layoutType attribute is needed. If you specify the layoutType, all the fields mentioned in layoutType (FULL or MINI) will be queried. If you specify array of fields ( field attribute ), only the specified fields will be queried.
Saving a record,
To save a record using Lightning Data Service, call saveRecord on the force:recordData component, and pass in a callback function to be invoked after the save operation completes.
In short, we need to do the following to save a record,
- Load the record in Edit mode using force:recordData to get the latest version of record. (All the updates to the record are hold in Edit mode.)
- call saveRecord and pass in a callback function to be invoked after the save operation (this callback can be optional)
you need to find the aura:id of force:recordData and call saveRecord to update the record. If we want to perform any operation or to check the status of save operation, pass in a callback function and check the status.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | handleSaveRecord: function(component, event, helper) { component.find("recordHandler").saveRecord($A.getCallback(function(saveResult) { // NOTE: If you want a specific behavior(an action or UI behavior) when this action is successful // then handle that in a callback (generic logic when record is changed should be handled in recordUpdated event handler) if (saveResult.state === "SUCCESS" || saveResult.state === "DRAFT") { // handle component related logic in event handler } else if (saveResult.state === "INCOMPLETE") { console.log("User is offline, device doesn't support drafts."); } else if (saveResult.state === "ERROR") { console.log('Problem saving record, error: ' + JSON.stringify(saveResult.error)); } else { console.log('Unknown problem, state: ' + saveResult.state + ', error: ' + JSON.stringify(saveResult.error)); } })); }, |
If there is a confusion or not able to understand, I am sure the following example will clear all your doubts.
Example of Lightning Data Service :
Use Case: Create a Lightning Quick Action to display Account Name, Industry and Description using Lightning Data Service. User should be able to update Account Name, Industry and Description and display the records.
What we need to achieve this ?
- Lightning Component (typically 3 components)
- LightningDataServiceExample – To load the record
- LightningEditComponent – To edit the record
- LightningContainer – To toggle base and edit components
- Lightning Quick Action on Account Object
Step 1:
Create a component with name LightningDataServiceExample.cmp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 | <aura:component implements="flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,force:lightningQuickAction" access="global" > <aura:attribute name="recordError" type="String"/> <aura:attribute name="recordInfo" type="Object" /> <aura:attribute name="simpleRecord" type="Object"/> <aura:attribute name="recordId" type="String"/> <aura:attribute name="curView" type="String" /> <force:recordData aura:id="recordLoader" recordId="{!v.recordId}" layoutType="FULL" targetRecord="{!v.recordInfo}" targetFields="{!v.simpleRecord}" targetError="{!v.recordError}" /> <div class="slds-form--stacked"> <div class="slds-form-element"> <label class="slds-form-element__label" for="recordName">Account Name</label> <div class="slds-form-element__control"> <ui:outputText value="{!v.simpleRecord.Name}" aura:id="accName"/> </div> </div> <div class="slds-form-element"> <label class="slds-form-element__label" for="recordOwnerName">Industry</label> <div class="slds-form-element__control"> <ui:outputText value="{!v.simpleRecord.Industry}" aura:id="accIndustry"/> </div> </div> <div class="slds-form-element"> <label class="slds-form-element__label" for="accType">Description </label> <div class="slds-form-element__control"> <ui:outputText value="{!v.simpleRecord.Description}" aura:id="accDesc"/> </div> </div> <div class="slds-form-element"> <lightning:button label="Edit Account" onclick="{!c.editRecordHandler}"/> </div> </div> </aura:component> |
LightningDataServiceExampleController.js
1 2 3 4 5 6 7 8 9 | ({ editRecordHandler : function(component, event, helper) { component.set("v.curView", "editView"); } }) |
Step 2: Create a component to update with name LightningDataServiceEdit
LightningDataServiceEdit.cmp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | <aura:component implements="flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,force:lightningQuickAction" access="global"> <aura:attribute name="recordError" type="String"/> <aura:attribute name="recordInfo" type="Object" /> <aura:attribute name="simpleRecord" type="Object"/> <aura:attribute name="curView" type="String" /> <force:recordData aura:id="recordHandler" recordId="{!v.recordId}" layoutType="FULL" targetRecord="{!v.recordInfo}" targetFields="{!v.simpleRecord}" mode="EDIT" /> <div class="slds-form--stacked"> <div class="slds-form-element"> <lightning:input type="text" label="Name" value="{!v.simpleRecord.Name}" /> </div> <div class="slds-form-element"> <lightning:select aura:id="accDesc" label="Industry" value="{!v.simpleRecord.Industry}"> <option value="">choose one...</option> <option value="Banking">Banking</option> <option value="Apparel">Apparel</option> <option value="Education">Education</option> </lightning:select> </div> <div class="slds-form-element"> <lightning:input type="text" label="Description" value="{!v.simpleRecord.Description}" /> </div> <div class="slds-form-element"> <lightning:button variant="brand" label="Save" onclick="{!c.saveRecordCntrlr}"/> <lightning:button label="Cancel" onclick="{!c.cancelSaveRecord}"/> </div> </div> </aura:component> |
Add below code in controller – LightningDataServiceEditController.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | ({ saveRecordCntrlr : function(component, event, helper) { component.find("recordHandler").saveRecord($A.getCallback(function(saveResult) { if (saveResult.state === "SUCCESS" || saveResult.state === "DRAFT") { console.log('recordSaved'); component.set("v.curView", "baseView" ); } else if (saveResult.state === "INCOMPLETE") { console.log("User is offline, device doesn't support drafts."); } else if (saveResult.state === "ERROR") { console.log('Problem saving record, error: ' + JSON.stringify(saveResult.error)); } else { console.log('Unknown problem, state: ' + saveResult.state + ', error: ' + JSON.stringify(saveResult.error)); } })); }, cancelSaveRecord : function(component, event, helper){ component.set("v.curView", "baseView" ); } }) |
Step 3: Now add the container component to toggle above two components ( base view and edit view ).
LDSContainer.cmp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | <aura:component implements="flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,force:lightningQuickActionWithoutHeader" access="global" > <aura:attribute name="currentView" type="String" default="baseView" /> <aura:if isTrue="{!v.currentView == 'baseView'}"> <c:LightningDataServiceExample recordId="{!v.recordId}" curView="{!v.currentView}" /> </aura:if> <aura:if isTrue="{!v.currentView == 'editView'}"> <c:LightningDataServiceEdit recordId="{!v.recordId}" curView="{!v.currentView}" /> </aura:if> </aura:component> |
Step 4: Create a lightning quick action add to the page layout.
( If you are new, check this on how to create a quick action )
Step 5: Test the component.
Refresh the Account page and select any record. You will see the magic.
Of course, you can apply better styling to look much better and can add toast message to notify users on update and what not.
Limitations:
- Lightning Data Service is only available in Lightning Experience and Salesforce1.
- We can only perform primitive DML operations (create, read, edit and delete ) on only one record. Bulk operations are not supported.
- Unfortunately, all the objects are not supported, Check this for the list of supported objects.
- Lightning Data Service is available as a beta. Lightning Data Service isn’t generally available unless or until Salesforce announces its general availability in documentation or in press releases or public statements.
That’s it for now. Happy Coding !! Cheers !!
Iron Man-Etrian | Titanium Bike, Skate, Bicycle - iTanium Art
ReplyDeleteIron Man is a trademark titanium apple watch of SEGA and was filed on ti89 titanium calculator March titanium tv apk 4, 2016. babylisspro nano titanium spring curling iron This sia titanium trademark was filed on September 5, 2016 in Stock.