Lightning Data Service - Salesforce new Apex alternative - Part 1

Lightning Data Service which is currently in Beta are Salesforce new alternative of using Apex in Lightning Components. Basically we can perform View, Save, Update, and Delete of any sObject record in Lightning Components without using Apex Code!

Lightning Data Service also respect org sharing rules and FLS settings, records that are loaded in LDS are cached and shared across components and components accessing same record see significant performance change, since the record is loaded only once and it doesn't matter how many components are using it. When one component updates a record, the other component using it are notified and refresh it automatically.

Resource Link: Lightning Data Service


Lets have a look at how Lightning Data Service works in Lightning Components.

1. Loading a Record:
This is the foremost simplest that we can do using LDS. Here force:recordData tag is what we use in our component and that is the key for our component to load record. Every force:recordData tag should specify following three parameter
  • ID of the record to load
  • Component attribute to assign the loaded record
  • List of fields to load
Below is the Lighting Component that will implement Lightning Data Service to display some data and we use Lightning Component Action on Account Object to expose our Component.

To Create a Component: Open Developer Console, navigate to File-->New-->Lightning Component and give some name for your Lighting Component and hit Submit. Now copy paste below code into your Component and Save.
1:  <aura:component implements="flexipage:availableForAllPageTypes,force:lightningQuickActionWithoutHeader,force:hasRecordId">  
2:    <!--Load LDS from static resource-->  
3:    <ltng:require styles="/resource/SLDS/assets/styles/salesforce-lightning-design-system.css"/>  
4:    <!--attributes to store record related information-->  
5:    <aura:attribute name="record" type="Object"/>  
6:    <aura:attribute name="simpleRecord" type="Object"/>  
7:    <aura:attribute name="recordError" type="String"/>  
8:    <h1 style="color:blue;font-family:verdana;">Test Lightning Data Service: Loading Record</h1>  
9:    <!--LDS to display record data-->  
10:    <force:recordData aura:id="recordLoader"  
11:             recordId="{!v.recordId}"  
12:             layoutType="FULL"  
13:             targetRecord="{!v.record}"   
14:             targetFields="{!v.simpleRecord}"  
15:             targetError="{!v.recordError}"  
16:             />  
17:       <!--Disply record data obtained from above LDS using Card component-->    
18:    <div class="slds-page-header" role="banner">  
19:      <b>Record Id:</b> <p class="slds-text-heading--label">{!v.simpleRecord.Id}</p>  
20:    </div>  
21:    <div class="slds-page-header" role="banner">  
22:      <b>Record Name:</b> <p class="slds-text-heading--label">{!v.simpleRecord.Name}</p>  
23:    </div>  
24:    <div class="slds-page-header" role="banner">  
25:      <b>Owner Name:</b> <p class="slds-text-heading--label">{!v.simpleRecord.Owner.Name}</p>  
26:    </div>   
27:    <div class="slds-page-header" role="banner">  
28:      <b>Created Date:</b> <p class="slds-text-heading--label">{!v.simpleRecord.CreatedDate}</p>  
29:    </div>  
30:  </aura:component>  

Once we have our above Component created, we go ahead and create a custom lightning component action on Account object and place it on Salesforce1 and Lightning Experience Actions section.




Now that we have out our component with action placed on Account Page, we should be able to view data for specific record using Lightning Design System by accessing custom action that we just created.


2. Updating a Record:
In order to save any record using LDS, we use force:recordData that we did with above LDS to view record data and here we are going to set Mode="EDIT" attribute and that is what exposes our LDS to update fields for a specific record in lighting component. Below we are going to create LDS_Save_Record and pull it on to the Account detail page to update few fields.

LDS_Save_Record.cmp Code:
1:  <aura:component implements="flexipage:availableForAllPageTypes,force:lightningQuickActionWithoutHeader,force:hasRecordId">  
2:    <!--Load LDS from static resource-->  
3:    <ltng:require styles="/resource/SLDS/assets/styles/salesforce-lightning-design-system.css"/>  
4:    <!--attributes to store record related information-->  
5:    <aura:attribute name="record" type="Object"/>  
6:    <aura:attribute name="simpleRecord" type="Object"/>  
7:    <aura:attribute name="recordError" type="String"/>  
8:    <p><b><h1 style="color:blue;font-family:verdana;">Test Lightning Data Service: Save Record!</h1></b></p>  
9:    <!--LDS to display record data-->  
10:    <force:recordData aura:id="record"  
11:             recordId="{!v.recordId}"  
12:             layoutType="FULL"  
13:             targetRecord="{!v.record}"   
14:             targetFields="{!v.simpleRecord}"  
15:             targetError="{!v.recordError}"  
16:             mode="EDIT"  
17:             />  
18:    <div class="slds-page-header" role="banner">    
19:      <lightning:input aura:id="recordName" name="recordName" label="Name" value="{!v.simpleRecord.Name}" required="false"/>  
20:    </div>  
21:    <div class="slds-page-header" role="banner">    
22:      <lightning:input aura:id="recordPhone" name="recordName" label="Phone" value="{!v.simpleRecord.Phone}" required="false"/>  
23:    </div>  
24:    <div class="slds-page-header" role="banner">    
25:      <lightning:input aura:id="recordWebsite" name="recordName" label="website" value="{!v.simpleRecord.Website}" required="false"/>  
26:    </div>  
27:    <div class="slds-page-header" role="banner">    
28:      <lightning:input aura:id="recordRating" name="recordName" label="Rating" value="{!v.simpleRecord.Rating}" required="false"/>  
29:    </div>      
30:    <center><lightning:button label="Save Record" onclick="{!c.handleSaveRecord}" variant="brand" class="slds-m-top--medium"/></center>  
31:  </aura:component>  

LDS_Save_Record.js code:
1:  ({  
2:    handleSaveRecord: function(component, event, helper) {  
3:      var resultsToast = $A.get("e.force:showToast");  
4:      //update current record      
5:      component.find("record").saveRecord($A.getCallback(function(saveResult) {  
6:        if (saveResult.state === "SUCCESS" || saveResult.state === "DRAFT") {   
7:          //display toast message upon success  
8:          resultsToast.setParams({  
9:            "title": "Current Record Id: " + component.get("v.recordId"),  
10:            "message": "Successfully updated current record."  
11:          });  
12:          resultsToast.fire();          
13:        } else if (saveResult.state === "INCOMPLETE") {  
14:          //display alert on incomplete state  
15:          alert('Incomplete!');  
16:        } else if (saveResult.state === "ERROR") {  
17:          //display alert on error state  
18:          alert('Error Occured');  
19:        } else {  
20:          //display some test alert as a default  
21:          alert('Testing Save');  
22:        }        
23:      }));      
24:    }      
25:  })  

Once we have our above component created, we place it on Account detail page using Lightning App Builder.

Now I should be able to update my Account data on Lighting Component using LDS that we just created and once save it should give me a success toast message. Here one more good thing is as soon as I update data successfully using component, I see the my Account standard detail field values are automatically refreshed to display changes that we did.



We will look into Creating and Deleting record using Lighting Design System in my next blog.

Hope you like reading this and any feedback or comments are really appreciated - Tks

Comments

Popular posts from this blog

Displaying Toast Message from Modal in Lightning Components

Lightning RecordForm - An enhanced Lightning Data Service

Lightning Component to display dynamic sObject data