In this blog, we are going to create a sample app which will list 10 recents accounts from Salesforce and will view and edit account using Lightning Data Services.
So lets start.
Create a “LDSAccountListViewApp” Lightning Application
<div class="maincontainer">
<div class="slds-col--padded slds-size--1-of-1 slds-medium--1-of-1 slds-large-size--1-of-1">
<div class="slds-form-element__control" >
<lightning:input label="Account Name" name="accname" value="{!v.fieldsInfo.Name}" />
</div>
</div>
<div class="slds-col--padded slds-size--1-of-1 slds-medium--1-of-1 slds-large-size--1-of-1">
<div class="slds-form-element__control" >
<lightning:input type="number" label="Annual Revenue" name="atype" value="{!v.fieldsInfo.AnnualRevenue}" formatter="currency"/>
</div>
</div>
<div class="slds-col--padded slds-size--1-of-1 slds-medium--1-of-1 slds-large-size--1-of-1">
<div class="slds-form-element__control" >
<lightning:input label="Account Number" name="accnum" value="{!v.fieldsInfo.AccountNumber}" />
</div>
</div>
<div class="slds-col--padded slds-size--1-of-1 slds-medium--1-of-1 slds-large-size--1-of-1">
<div class="slds-form-element__control" >
<lightning:button variant="brand" label="Save" onclick="{!c.saveRecordHandler}"/>
<lightning:button variant="brand" label="Back" />
</div>
</div>
</div>
So lets start.
Create a “LDSAccountListViewApp” Lightning Application
- In the Developer Console, choose File > New > Lightning Application.
- Specify “LDSAccountListViewApp” as the app name and click submit.
- Specify below code in lightning app.
<aura:application extends="force:slds">
<div class="slds-text-heading_large slds-text-align_center">
Lightning Data Service Demo App
</div>
</aura:application>
- Save the file.
- Click preview
Create a LDSAccountEdit lightning Component
- In the Developer Console, choose File > New > Lightning Component.
- Specify “LDSAccountEdit” as the component name and click submit. Paste below code and Save the file.
<aura:component >
<aura:attribute name="recordId" type="String" required="true"/>
<aura:attribute name="recordInfo" type="Object"/>
<aura:attribute name="fieldsInfo" type="Object"/>
<aura:attribute name="recordError" type="String"/>
<aura:attribute name="currView" type="String" />
<force:recordData aura:id="recordLoader"
recordId="{!v.recordId}"
mode="EDIT"
targetRecord="{!v.recordInfo}"
targetFields="{!v.fieldsInfo}" fields="Name,Owner.Name,AnnualRevenue,AccountNumber"
targetError="{!v.recordError}"
recordUpdated="{!c.handleRecordChanges}" />
<div class="maincontainer">
</div>
<!-- Display Lightning Data Service errors, if any -->
<aura:if isTrue="{!not(empty(v.recordError))}">
<div class="recordError">
<ui:message title="Error" severity="error" closable="true"> {!v.recordError} </ui:message>
</div>
</aura:if>
</aura:component>
- Click CONTROLLER in the right side bar of the code editor and replace code with below code and save the file.
({
handleRecordChanges: function(component, event, helper) {
var eventParams = event.getParams();
if(eventParams.changeType === "LOADED") {
// record is loaded
var fieldsDetails= component.get("v.fieldsInfo");
console.log("fieldsInfo is loaded successfully. TargetField"+ JSON.stringify(fieldsDetails));
var recordDetails= component.get("v.recordInfo");
console.log("recordInfo -Target Record"+ JSON.stringify(recordDetails));
console.log('Record loaded successfully');
}
}
})
- Update the “LDSAccountListViewApp” code with below code and save file.
<aura:application extends="force:slds">
<div class="slds-text-heading_large slds-text-align_center">
Lightning Data Service Demo App
</div>
<c:LDSAccountEdit recordId=“0017F000004R9C3QAK”/>
</aura:application>
Lets see what we have done!!!
- In order to display more account fields, replace the code inside div with class “maincontainer” with below code.
<div class="maincontainer">
<div class="slds-col--padded slds-size--1-of-1 slds-medium--1-of-1 slds-large-size--1-of-1">
<div class="slds-form-element__control" >
<lightning:input label="Account Name" name="accname" value="{!v.fieldsInfo.Name}" />
</div>
</div>
<div class="slds-col--padded slds-size--1-of-1 slds-medium--1-of-1 slds-large-size--1-of-1">
<div class="slds-form-element__control" >
<lightning:input type="number" label="Annual Revenue" name="atype" value="{!v.fieldsInfo.AnnualRevenue}" formatter="currency"/>
</div>
</div>
<div class="slds-col--padded slds-size--1-of-1 slds-medium--1-of-1 slds-large-size--1-of-1">
<div class="slds-form-element__control" >
<lightning:input label="Account Number" name="accnum" value="{!v.fieldsInfo.AccountNumber}" />
</div>
</div>
<div class="slds-col--padded slds-size--1-of-1 slds-medium--1-of-1 slds-large-size--1-of-1">
<div class="slds-form-element__control" >
<lightning:button variant="brand" label="Save" onclick="{!c.saveRecordHandler}"/>
<lightning:button variant="brand" label="Back" />
</div>
</div>
</div>
- Click CONTROLLER in the right side bar of the code editor and add saveRecordHandler function and save the file.
saveRecordHandler: function(component, event, helper) { component.find("recordLoader").saveRecord($A.getCallback(function(saveResult) {
if (saveResult.state === "SUCCESS" || saveResult.state === "DRAFT") { console.log('Record updated successfully');
}else if (saveResult.state === "ERROR") {
console.log('Problem error: ' + JSON.stringify(saveResult.error));
} else {
console.log('Unknown problem, state: ' + saveResult.state + ', error: ' + JSON.stringify(saveResult.error));
}
}));
}
- Update the “LDSAccountListViewApp” code with below code and save file.
<aura:application extends="force:slds">
<div class="slds-text-heading_large slds-text-align_center">
Lightning Data Service Demo App
</div>
<c:LDSAccountEdit recordId=“0017F000004R9C3QAK”/>
</aura:application>
Lets see what we have done!!!
Create a LDSAccountView lightning Component
- In the Developer Console, choose File > New > Lightning Component.
- Specify “LDSAccountView” as the component name and click submit.
- Copy the code from “LDSAccountEdit” component and paste it here.
- Add a attribute disabled="true" in all lightning:input tag
<lightning:input label="Account Name" name="accname" value="{!v.fieldsInfo.Name}" dsabled="true"/>
- Remove "handleRecordChanges" attribute from <force:recorddata> tag.
- Remove Lightning:button with label as "Save".
Complete code for LDSAccountView Component is :
<aura:component >
<aura:attribute name="recordId" type="String" required="true"/>
<aura:attribute name="recordInfo" type="Object"/>
<aura:attribute name="fieldsInfo" type="Object"/>
<aura:attribute name="currView" type="String" />
<aura:attribute name="recordError" type="String"/>
<force:recordData aura:id="recordLoader"
recordId="{!v.recordId}"
mode="VIEW"
targetRecord="{!v.recordInfo}"
targetFields="{!v.fieldsInfo}"
fields="Name,Owner.Name,AnnualRevenue,AccountNumber"
targetError="{!v.recordError}"
/>
<div class="maincontainer">
<div class="slds-col--padded slds-size--1-of-1 slds-medium--1-of-1 slds-large-size--1-of-1">
<div class="slds-form-element__control" >
<lightning:input label="Account Name" name="accname" value="{!v.fieldsInfo.Name}" disabled="true"/>
</div>
</div>
<div class="slds-col--padded slds-size--1-of-1 slds-medium--1-of-1 slds-large-size--1-of-1">
<div class="slds-form-element__control" >
<lightning:input type="number" label="Annual Revenue" name="atype" value="{!v.fieldsInfo.AnnualRevenue}" formatter="currency" disabled="true"/>
</div>
</div>
<div class="slds-col--padded slds-size--1-of-1 slds-medium--1-of-1 slds-large-size--1-of-1">
<div class="slds-form-element__control" >
<lightning:input label="Account Number" name="accnum" value="{!v.fieldsInfo.AccountNumber}" disabled="true"/>
</div>
</div>
<div class="slds-col--padded slds-size--1-of-1 slds-medium--1-of-1 slds-large-size--1-of-1">
<div class="slds-form-element__control" >
<!--<lightning:button variant="brand" label="Save" onclick="{!c.saveRecordHandler}"/> -->
<lightning:button variant="brand" label="Back" onclick="{!c.goBackToListView}"/>
</div>
</div>
</div>
<!-- Display Lightning Data Service errors, if any -->
<aura:if isTrue="{!not(empty(v.recordError))}">
<div class="recordError">
<ui:message title="Error" severity="error" closable="true">
{!v.recordError}
</ui:message>
</div>
</aura:if>
</aura:component>
- Update the “LDSAccountListViewApp” code with below code and save file.
<aura:application extends="force:slds">
<div class="slds-text-heading_large slds-text-align_center">
Lightning Data Service Demo App
</div>
<c:LDSAccountView recordId=“0017F000004R9C3QAK”/>
</aura:application>
Lets see what we have done!!
Create a Apex class to fetch Account records
- Create Apex Class “LDSAccountListViewController” to fetch latest 10 Account records from your org.
public with Sharing class LDSAccountListViewController {
@AuraEnabled public static List<Account> findAccounts(){
List<Account> accList = new List<Account>();
accList=[select id, name,owner.name,type,AccountNumber,AnnualRevenue,Phone from Account order by lastModifiedDate DESC Limit 10];
return accList;
}
}
Create a LDSAccountListView lightning Component
- In the Developer Console, choose File > New > Lightning Component.
- Specify “LDSAccountListView” as the component name and click submit.
<aura:component controller="LDSAccountListViewController" >
<aura:attribute name="accList" type="List" />
<aura:attribute name="menu" type="List" default="View,Edit"/>
<aura:attribute name="currentView" type="String" default="ListView"/>
<aura:attribute name="selectedRecord" type="String" />
<aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
<!--Section for Account List View starts-->
<aura:if isTrue="{!v.currentView =='ListView'}">
<div class="slds-card">
<div class="slds-card__header slds-grid">
<header class="slds-media slds-media_center slds-has-flexi-truncate">
<div class="slds-media__figure">
<lightning:Icon iconName="standard:account" size="large" variant="inverse" />
</div>
<div class="slds-media__body">
<h2> <span class="slds-text-heading_small">Accounts({!v.accList.length})</span> </h2>
</div>
</header>
<div class="slds-no-flex"> <lightning:button variant="brand" label="New Account" /> </div>
</div>
<div class="slds-card__body slds-card__body_inner">
<aura:if isTrue="{!v.accList.length > 0}"> <!--display all accounts--> </aura:if>
</div>
<footer class="slds-card__footer">@sunil02kumar</footer> </div>
</aura:if>
<!--Section for Account List View ends-->
</aura:component>
- Click CONTROLLER in the right side bar of the code editor and add doInit function and save the file
({
doInit : function(component, event, helper){
var action = component.get("c.findAccounts");
action.setCallback(this, function(response) {
var state = response.getState();
if (state === "SUCCESS") {
var apexResponse = response.getReturnValue();
//console.log('***apexResponse:'+ JSON.stringify(apexResponse));
component.set("v.accList", apexResponse);
console.log('********Accounts list view loaded successfully');
}else if(state === "ERROR"){
alert('Problem with connection. Please try again.');
}});
$A.enqueueAction(action);
}
})
- Update the “LDSAccountListViewApp” code with below code and save file.
<aura:application extends="force:slds">
<div class="slds-text-heading_large slds-text-align_center">
Lightning Data Service Demo App
</div>
<c:LDSAccountListView />
</aura:application>
- Update LDSAccountListView lightning Component. Replace <!--display all accounts--> section with below code and save file.
<table class="slds-table slds-table_fixed-layout slds-table_bordered slds-table_cell-buffer">
<thead>
<tr class="slds-text-title--caps">
<th scope="col">Actions</th>
<th scope="col">Name</th>
<th scope="col">Account Number</th>
</tr>
</thead>
<tbody>
<aura:iteration items="{!v.accList}" var="item">
<tr class="slds-hint-parent">
<td scope="row">
<lightning:buttonMenu iconName="utility:threedots" >
<aura:iteration items="{!v.menu}" var="menuItem">
<lightning:menuItem label="{!menuItem}" value="{!item.Id + '---' + menuItem}" onactive="{!c.onSelectMenuItem}"/>
</aura:iteration>
</lightning:buttonMenu>
</td>
<td > {!item.Name}</td>
<td > {!item.AccountNumber}</td>
</tr>
</aura:iteration>
</tbody>
</table>
- Click CONTROLLER in the right side bar of the code editor and add onSelectMenuItem function and save the file.
onSelectMenuItem : function(component, event, helper) {
var selectedOption = event.getSource().get('v.value');
var selectedId = selectedOption.split('---')[0];
console.log('*************selectedId:'+selectedId);
component.set("v.selectedRecord",selectedId);
console.log('*************selectedOption:'+selectedOption);
if (selectedOption.endsWith("View")) {
component.set("v.currentView","RecordView");
}else if(selectedOption.endsWith("Edit")){
component.set("v.currentView","RecordEdit");
}
}
- Update LDSAccountListView lightning Component. Now we are going to display LDSAccountView and LDSAccountEdit components based selection made by user on menu item. Add below markup code in LDSAccountListView component after the section for account list views and save file.
<!--Section for Account record View starts-->
<aura:if isTrue="{!v.currentView =='RecordView'}">
<c:LDSAccountView recordId="{!v.selectedRecord}" currView="{!v.currentView}"/> </aura:if>
<!--Section for Account record View ends-->
<!--Section for Account record edit starts-->
<aura:if isTrue="{!v.currentView =='RecordEdit'}">
<c:LDSAccountEdit recordId="{!v.selectedRecord}" currView="{!v.currentView}" /> </aura:if>
<!--Section for Account record edit ends-->
Update LDSAccountView & LDSAccountView lightning Component
- In LDSAccountEdit component, add action to lightning:button with label as "Back".
<lightning:button variant="brand" label="Back" onclick="{!c.goBackToListView}"/>
- Click CONTROLLER in the right side bar of the code editor and add goBackToListViewfunction and save the file.
goBackToListView : function(component,event,helper){
component.set("v.currView","ListView");
}
- Same way in LDSAccountView, update lightning:button with label as "Back" and add "goBackToListView" JavaScript function to controller.
Let see what we have done so far!!!
So now we are loading account view and edit page using Lightning Data Services. I think this will help you to understand basic concept of Lightning data services.
Below are list of items which can be implemented to for better User experience and for learning.
- You can add deletion of records using LDS.
- When you click on Save in account edit page, it should refresh the list view with latest changes. In this hands on training you have to refresh the browser to see latest values of account record.
- You can use "New Account" to create new account record using LDS.
Hope this will help in basic understanding of Lightning Data Services!!!.
I was really happy to visit your blog, This blog is decent and very attractive. Thank you so much for your sharing with us...
ReplyDeleteTableau Training in Chennai
Tableau Course in Chennai
Pega Training in Chennai
Excel Training in Chennai
Power BI Training in Chennai
Primavera Training in Chennai
Unix Training in Chennai
Tableau Training in Chennai
Tableau Course in Chennai
Outstanding blog with lots of information. Keep posting more like this. keep update this
ReplyDeleteAi & Artificial Intelligence Course in Chennai
PHP Training in Chennai
Ethical Hacking Course in Chennai Blue Prism Training in Chennai
UiPath Training in Chennai
Nice post. Thanks for sharing! I want people to know just how good this information is in your article. It’s interesting content and Great work. great wrk
ReplyDeleteAi & Artificial Intelligence Course in Chennai
PHP Training in Chennai
Ethical Hacking Course in Chennai Blue Prism Training in Chennai
UiPath Training in Chennai
It is actually a great and helpful piece of information. we provide audio hire Melbourne at affordable prices. for more info visit our website.
ReplyDelete
ReplyDeleteNice blog! Thanks for sharing this valuable information
German Classes in Bangalore
German Language Course in Bangalore
German Language Course in Hyderabad
German Language Course in Delhi
German Language Classes in Pune
Excellent Information! keep updating your Blog
ReplyDeleteBig Data training and placement in Bangalore
Hadoop Training in Chennai
vé máy bay đi Mỹ khứ hồi
ReplyDeletemua vé máy bay từ mỹ về việt nam hãng eva
vé máy bay từ đức về việt nam
dịch vụ vé máy bay tại nga
giá thuê máy bay từ anh về việt nam
chuyến bay từ paris về hà nội
Great post. keep sharing such a worthy information
ReplyDeleteEthical Hacking Course in Chennai Ethical Hacking course in Bangalore
Fabulous blog keep updating like this.....
ReplyDeleteBest DevOps Training in Chennai
DevOps Training institute in Chennai
DevOps Course in Bangalore
DevOps Training Institutes in Bangalore
very informative blogs posting thanks you so much sharing me information.
ReplyDeleteGerman language Course In Chandigarh
Great post. keep sharing such a worthy information.
ReplyDeleteif you want to buy zirconia crowns in india . dental direkt is best choice for you .
This comment has been removed by the author.
ReplyDeleteVery nice post here and thanks for it .I always like and such a super contents of these post. Excellent and very cool idea and great content of different kinds of the valuable information's.
ReplyDeleteif you want to buy best zirconia crowns in india . dental direkt is best choice for you .
Thank you so much for such a well-written article. It’s full of insightful information
ReplyDeleteZirconia Crown Manufacturer In India
I really appreciate the kind of topics you post here, a great information that is actually helpful for us and you can also visit our link for best zirconia crowns in india
ReplyDeleteAre you still unsuccessful in your search for the top online data science courses? Several platforms provide data science courses, but it's crucial to focus on those that meet your requirements and allow for domain specialisation. A few training opportunities in data science are included below for those who are just entering the profession.data science course institute in nagpur
ReplyDeleteThanks! Very interesting to read. This is really very helpful. Top 8 Best Data Science Course In Lucknow
ReplyDelete