Skip to main content

Salesforce Lightning Data Service

In this blog, Today we can learn about the Lightning Data Service.
  1. What is Lightning Data Service?
  2. Why to use Lightning Data Service?
  3. When to use Lightning Data Service?
  4. Which Lightning Data Service to use?

What is Lightning Data Service?

Lightning Data Service is centralized data caching framework, which is use to load, create, update and delete the data in Salesforce without Salesforce Server side Apex Code.


Why to use Lightning Data Service?

Below are the few reasons of using Lightning Data Service in Lightning Web Component:
  • No need of additional apex code to get data by making additional server side call.
  • Lightning Data Service supports Sharing Rule and Field Level Security.
  • Because of not writing additional Apex Class code, it will improve component's performance.
  • It cache the result locally on Client Side.
  • It supports all standard and custom Objects of Salesforce.
When to use Lightning Data Service?

Below are the scenarios when we can use Lightning Data Service in LWC:
  1. Load a record
  2. Edit a record
  3. Create a record
Which Lightning Data Service to use?

Below are the 3 possible ways which allows user to view, edit and create records in Salesforce:
  1. lightning-record-form
  2. lightning-record-edit-form
  3. lightning-record-view-form
If above 3 options are not giving you enough flexibility then use wire service.
Let us fill below table after understanding each use case.

Scenario    lightning-record-form    lightning-record-edit-form    lightning-record-view-form     
    

Scenario 1: Load Record

If user want to load a record in Salesforce. Then User can go with below 2 base components:
  • lightning-record-form: Using this base component we just need to pass the record Id and we will get the exact same layout of the record. If you want to show specific fields on component then also we can use this base component.
In below example we have passed the record Id of Account record to lightning-record-form. 
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
<template>
    <div style="background-color: white;" class="slds-p-around_x-small">
        <lightning-card  variant="Narrow"  title="Account (lightning-record-form)" icon-name="standard:account">
            <div class="slds-p-horizontal_small">
                <lightning-record-form record-id={recordId} object-api-name="Account" layout-type="Full" mode="view">
                </lightning-record-form>
            </div>
        </lightning-card>
    </div>
</template>

1
2
3
4
5
import { LightningElement, api} from 'lwc';

export default class LightningDataServiceExamples extends LightningElement {
    @api recordId = '0017F00002MfGO9QAN';
}

So in case if we need to show actual record page layout then lightning-record-form. 
  • lightning-record-view-form: Now we can use lightning-record-view-form also for loading Salesforce data. But it will not show actual layout of the record. If user want specific field of any record then we can go with this option.
In below example also we are using same Java Script which we have used in above example. 
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
<template>
    <div style="background-color: white;" class="slds-p-around_x-small">
        <lightning-card  variant="Narrow"  title="Account (lightning-record-view-form)" icon-name="standard:account">
            <div class="slds-p-horizontal_small">
                <lightning-record-view-form record-id={recordId} object-api-name="Account">
                    <div class="slds-grid">
                        <div class="slds-col slds-size_1-of-2">
                            <lightning-output-field field-name="Name"></lightning-output-field>
                            <lightning-output-field field-name="Phone"></lightning-output-field>
                        </div>
                        <div class="slds-col slds-size_1-of-2">
                            <lightning-output-field field-name="Industry"></lightning-output-field>
                            <lightning-output-field field-name="AnnualRevenue"></lightning-output-field>
                        </div>
                    </div>
                </lightning-record-view-form>
            </div>
        </lightning-card>
    </div>
</template>


Now let us see what is the difference in both base component in loading data.

 Scenario

lightning-record-form
lightning-record-view-form
 Load Data    Yes Yes 
 Edit Data  Yes  No
 Inline EditingYesNo
 View only DataYesYes
 Show actual record page layout Yes  Yes (But need to add all fields manually - not preferred)
 Show specific field of recordYesYes
 Display custom page layout**NoYes
 Show formatted dataNo Yes (Use getRecord or getRecordUI wire adapter)

** Custom Page Layout means we can customise page layout in lightning-record-view-form but we cannot customise lightning-record-form. In customisation we can show data in different sections, use lightning-formatted-text to customise data etc.



Scenario 2: Edit Record

To edit Salesforce record we can use below 2 base components:
  • lightning-record-form:  This base component will give you actual record page layout in edit mode. Also we can specify set-of field which we want to see in edit mode of record.
This is exact same as above code which we used for loading data. The only difference is the value of mode attribute on lightning-record-form tag which is EDIT.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
<template>
    <div style="background-color: white;" class="slds-p-around_x-small">
        <lightning-card  variant="Narrow"  title="Account (lightning-record-form)" icon-name="standard:account">
            <div class="slds-p-horizontal_small">
                <lightning-record-form record-id={recordId} object-api-name="Account" layout-type="Full" mode="edit">
                </lightning-record-form>
            </div>
        </lightning-card>
    </div>
</template>

If you want to specify specific field in lightning-record-form then import field using schema api to get field informations.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
<template>
    <div style="background-color: white;" class="slds-p-around_x-small">
        <lightning-card  variant="Narrow"  title="Account (lightning-record-form for specific fields)" icon-name="standard:account">
            <div class="slds-p-horizontal_small">
                <lightning-record-form record-id={recordId} object-api-name="Account" fields={fields}>
                </lightning-record-form>
            </div>
        </lightning-card>
    </div>
</template>

Below is the Javascript to get the specific fields information:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
import { LightningElement, api} from 'lwc';
import ACCOUNT_ID from '@salesforce/schema/Account.Id';
import ACCOUNT_NAME from '@salesforce/schema/Account.Name';
import ACCOUNT_PHONE from '@salesforce/schema/Account.Phone';
import ACCOUNT_TYPE from '@salesforce/schema/Account.Type';
import ACCOUNT_WEBSITE from '@salesforce/schema/Account.Website';


export default class LightningDataServiceExamples extends LightningElement {
    @api recordId = '0017F00002MfGO9QAN';
    fields = [ACCOUNT_ID, ACCOUNT_NAME, ACCOUNT_PHONE, ACCOUNT_TYPE, ACCOUNT_WEBSITE];
}

  • lightning-record-edit-form:  This base component cannot show full record edit page by passing record id. But we can create custom page layout using this base component.
Also using this lightning-record-edit-form we can use field reset functionality which is not possible in lightning-record-form.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
<template>
    <lightning-record-edit-form
        object-api-name='Account'
        record-id={recordId}>
    <lightning-messages></lightning-messages>
    <div class="slds-grid">
        <div class="slds-col slds-size_1-of-2">
            <lightning-input-field field-name="Name"></lightning-input-field>
            <lightning-input-field field-name="Title"></lightning-input-field>
        </div>
        <div class="slds-col slds-size_1-of-2">
            <lightning-input-field field-name="Website"></lightning-input-field>
            <lightning-input-field field-name="Type"></lightning-input-field>
        </div>
    </div>
    <div class="slds-m-top_medium">
        <lightning-button type="submit" variant="brand" label="Save Account"></lightning-button>
    </div>
</template>

 Scenario    lightning-record-formlightning-record-edit-form
 Edit Data     Yes  Yes
 Edit specific fields of recordYes Yes
 Reset fields valuesNo Yes
 Customise ComponentNo Yes
 Overriding default save behaviourNo  Yes


Scenario 3: Create Record

Creating record is similar to Editing record. The only difference is for record creation we don't need to pass record-id value to lightning-record-form or lightning-record-edit-form. 

 Scenario    lightning-record-formlightning-record-edit-form
 Create Data     Yes  Yes
 Create data with specific fieldsYes Yes
 Reset fields valuesNo Yes
 Customise ComponentNo Yes
 Overriding default save behaviourNo  Yes


Now let's take a look on all scenarios and see when to use which lightning base component:

Scenario    lightning-record-form    lightning-record-edit-form    lightning-record-view-form     
 Create data Yes Yes No
 Create data with specific fields Yes Yes No
 Create data with custom layout No  Yes No
 Override default behaviour during record creation No Yes No 
 Edit data Yes Yes No
 Edit data with specific fields Yes Yes No
 Edit data with custom layout No Yes No
 Override default behaviour during record edit No Yes No
 View data Yes No Yes
 View data with specific fields Yes No Yes
 View data with custom layout No No Yes

Apart from these base component we can use wire service from which we can create, update and delete the Salesforce data without using apex code.

Comments

Popular posts from this blog

Get started with Simple Lightning Web Component(Bike Card)

Lightning web component HTML files all include the template tag. The template tag contains the HTML that defines the structure of your component. Let’s look at the HTML for a simplified version of the component. Paste the following into app.html (replacing any existing HTML in the file). bikeCard.html < template > < div id = "waiting" if : false = { ready } > Loading.. </ div > < div id = "dispaly" if : true = { ready } > < div > Name: {name} </ div > < div > Description: {description} </ div > < div > Category: {category} </ div > < div > Material: {material} </ div > < div > Price: {price} </ div > < div >< img src = { pictureURL } /></ div > </ div > </ template > The identifiers in the curly braces {} are bound to the fields of the same name in the corresponding JavaScript class. Here’s a JavaScript file to s...

Disable Document Download in Salesforce

Disable downloads for certain users based on the name of the file uploaded to Salesforce. We can use the following example code inside of a Apex class. This code essentially prevents files whose file name starts off with Kaipu- from being downloaded by anyone whose user role’s developer name is not Kaipu_Sales. Modify this code to suit your own purpose. Based on Role: public class ContentDownloadHandlerFactoryImpl implements Sfc.ContentDownloadHandlerFactory {    public Sfc.ContentDownloadHandler getContentDownloadHandler(List<ID> ids, Sfc.ContentDownloadContext context) {      // See if the user has the Kaipu Sales role (based on developer name field).      Boolean isSecretUser = [        SELECT Id        FROM UserRole        WHERE ID = :UserInfo.getUserRoleId()          AND DeveloperName = ' Kaip...

Commonly asked Lightning Developer Interview Questions & Answers

1. Where can we use Lightning Components? We can use Lightning Components in the following places: Drag-and-drop Components in the Lightning App Builder and Community Builder. Add Lightning Components to Lightning Pages. Add Lightning Components to Lightning Experience Record Pages. Launch a Lightning Component as a Quick Action Override Standard Actions with Lightning Components Create Stand-Alone Apps 2. How do you build Lightning Components? We can build Lightning Components using two programming models: the Lightning Web Components model, and the original Aura Components model. 3. How can you create Lightning Record Pages in Salesforce, and what are the different types? We can make use of Lightning App Builder for creating Lightning Record Pages, to create the following three types of pages: App Page Home Page Record Page 4. What options are there for Lightning Record Page assignment? “Lightning Pages” can be assigned at three different levels: The org default App default – this ov...