Lightning Web Components (LWC) has revolutionised the way developers build application on the salesforce platform. LWC utilizes modern web development standards which makes it very easy for developers to build a fast paced, scalable and responsive web and mobile applications. This has made javascript pretty easy to non-tech background persons as well. And the heart of this revolution is a framework which we call as Lightning Data Service (LDS).
What is Lightning Data Service ?
In layman language we can call LDS as a client-side data caching mechanism which can be utilized to fetch data or perform CRUD (create, read, update, delete) operations on the record from the JS itself without using server side apex class to perform database operations.
Benefits of using Lightning Data Service
- No server side (apex) calling required for CRUD: We can easily perform create, read, update, and delete operations from within your LWC components only without relying on Apex Class controllers.
- Client Side Data Caching: Since we know that LDS is a caching mechanism so it basically caches frequently accessed data in the local browser memory which reduces multiple round trips to server side and this significantly improves the performance and user experience.
- Very Easy & Automated Error Handling: It has a built-in error handling mechanism which automatically handles errors and exceptions.
- Offline Capability: It works even in offline mode as well hence covering offline capability scenario as well.
- Improved Developer Productivity: Since we don’t have to write Apex code, it becomes very easy for developers to focus on building the user interface without hassle.
Lets Perform CRUD Operations with LDS
We will apply LDS in fetching data (getRecord), creating the record form (createRecord) & update the existing record (updateRecord) without writing any apex code.
This is how we import all the three :
import { LightningElement, api, track, wire } from 'lwc';
import { createRecord, getRecord, updateRecord } from 'lightning/uiRecordApi';
Lets start will individual operation beginning with getRecord :
We have fetched above details from an account record id using the getRecord :
JS :
import { LightningElement, wire, api } from 'lwc';
//1. Import methods -> getRecord and getFieldValue
import { getRecord, getFieldValue } from "lightning/uiRecordApi";
//2. Import reference to the object and the fields
import NAME_FIELD from "@salesforce/schema/Account.Name";
import RATING_FIELD from "@salesforce/schema/Account.Rating";
import INDUSTRY_FIELD from "@salesforce/schema/Account.Industry";
const fields = [NAME_FIELD, RATING_FIELD, INDUSTRY_FIELD];
export default class LdsGetRecord extends LightningElement {
@api
recordId = '0015i00000TVZNjAAP';
//3. Wire the output of the out of the box method getRecord to the property account
@wire(getRecord, {
recordId: "$recordId",
fields
})
account;
renderedCallback() {
console.log(this.account.data);
}
//4. Fetch the field values from the record
get name() {
return getFieldValue(this.account.data, NAME_FIELD);
}
get rating() {
return getFieldValue(this.account.data, RATING_FIELD);
}
get industry() {
return getFieldValue(this.account.data, INDUSTRY_FIELD);
}
}
HTML :
Account Industry : {industry}
Account Rating : {rating}
Meta-XML :
<?xml version="1.0"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<masterLabel>lds get record</masterLabel>
<apiVersion>60.0</apiVersion>
<isExposed>true</isExposed>
<targets>
<target>lightning__AppPage</target>
</targets>
</LightningComponentBundle>
Note: In case we want to retrieve multiple records , use -> “getRecords”, to learn more click here
Now, lets jump to createRecord
Here, in order to create a record we need a UI where we can provude user inputs such as Name, Industry , Email etc etc..
Here, we have to take help of something called Base lightning components which are basically build on top of lightning Data Service.
What are base lightning components ?
There are three types :
- lightning-record-form: This is a form which has a standard lightning UI and is used to create, view or edit a record. Official documentation here.
- lightning-record-edit-form: This is a form which is used to create record with specified fields or update fields in an existing record. Official documentation here.
- lightning-record-view-form: This is a form which is used to display specific fields data of a record in read-only mode
First, lets understand lightning-record-form :
Create this form and provide recordId and object Name and it will automatically fetch details:
Since Lead source is blank, lets put some value, when you will click on edit/pencil icon, below ui will appear and you can edit and save the record.
now after saving we can see :
JS:
import { LightningElement, api } from 'lwc';
import NAME_FIELD from '@salesforce/schema/Contact.Name';
import PHONE_FIELD from '@salesforce/schema/Contact.Phone';
import EMAIL_FIELD from '@salesforce/schema/Contact.Email';
import LEAD_FIELD from '@salesforce/schema/Contact.LeadSource';
// in case iwe want to use in a managed package with your custom object
//import MY_CUSTOM_OBJECT from '@salesforce/schema/namespace__Custom_object__c';
export default class LightningRecordForm extends LightningElement {
// Expose a field to make it available in the template
fields = [NAME_FIELD,PHONE_FIELD,EMAIL_FIELD,LEAD_FIELD];
// Flexipage provides recordId and objectApiName
@api recordId = '0035i000012ONzMAAW';
@api objectApiName = 'Contact';
}
HTML :
Meta-xml :
<?xml version="1.0"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<masterLabel>lightning record form</masterLabel>
<apiVersion>60.0</apiVersion>
<isExposed>true</isExposed>
<targets>
<target>lightning__AppPage</target>
</targets>
</LightningComponentBundle>
Lets assume instead of only these few fields, we want to see all the fields , in that case we can add -> layout-type=”Full” :
<div class="slds-p-left_medium">
<lightning-record-form
object-api-name={objectApiName}
record-id={recordId}
fields={fields}
layout-type="Full"
>
</lightning-record-form>
</div>
Then our form will look like :
Similarly we can add mode=”View”, mode=”edit” as well in case of different scenarios. You can check the official documentation for further details from here
In case of custom form development we can utilize createRecord by passing the fields:
createRecord({ apiName: 'Account', fields: { Name: 'New Account' } })
.then(result => {
// Handle success
})
.catch(error => {
// Handle error
});
in case of updateRecord :
updateRecord({ fields: { Id: recordId, Name: 'Updated Name' } })
.then(result => {
// Handle success
})
.catch(error => {
// Handle error
});
in case of delete:
Here, please note, there is no direct way of deleting a record from LDS, one way to do that is we utilize the updateRecords with value ‘IsDeleted = true’.
So, you can follow the above given steps to build standard or custom forms, take user inputs and utilize standard Lightning data services and minimise apex coding dependency and then you wont be needing to write apex classes which in turn save a lot of time.
Enjoy coding, i would like all the practitioners to go through this important topic which is related to aggregate queries by clicking here . This will be very useful in your daily coding activities. If you get stuck anywhere, please feel free to reach me out..