Lightning Data Service for Lightning Web Components
Explore the potential of Lightning Data Service in Lightning Web Components through its three core features: base components, wire adapters, and wire functions.
Join the DZone community and get the full member experience.
Join For FreeWhen developing Lightning Web Components (LWC) in Salesforce, working with data efficiently is key to building powerful and scalable applications. Salesforce provides several ways to retrieve and manipulate data within LWC, and one of the most effective methods is using Lightning Data Service (LDS).
LDS allows you to interact with Salesforce data — whether it’s retrieving, modifying, or deleting — without the need for any Apex code. It also offers a built-in cache that is shared across components, ensuring that data changes made by one component are automatically reflected in others, enhancing synchronization and reducing redundancy.
There are three core features of LDS that you can leverage:
- Base lightning components – Pre-built components that utilize LDS
- LDS wire adapters – Methods to read data and metadata
- LDS functions – Functions to modify data in Salesforce
In the following sections, we will explore these features in greater detail and provide examples to illustrate how they can be used effectively.
1. LDS Base Components
When working with a single record, you can use the following three base components provided by LDS to manipulate the data.
lightning-record-form
This component enables you to add, view, or edit records. The fields displayed are defined by an admin-configured layout or an ordered list of fields passed to the component. object-api-name
is a required attribute, while record-id
is only necessary when editing or viewing a record.
Save and cancel buttons are automatically provided when the form is used for editing a record. However, please note that this form offers limited customization compared to the view/edit base components. For more details, refer to this link.
Here is an example of using lightning-record-form
to build a form that creates lead records in Salesforce. The object-api-name
and fields
attribute is passed to build the lead form.
<template>
<lightning-card title = "Lead Create Form">
<lightning-record-form
object-api-name={objectApiName}
fields={fields}
onsuccess={handleSuccess}>
</lightning-record-form>
</lightning-card>
</template>
import { LightningElement } from 'lwc';
import LEAD_OBJECT from '@salesforce/schema/Lead';
import FIRST_NAME from '@salesforce/schema/Lead.FirstName';
import LAST_NAME from '@salesforce/schema/Lead.LastName';
import PHONE from '@salesforce/schema/Lead.Phone';
import COMPANY from '@salesforce/schema/Lead.Company';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
export default class Lds_base_comp_create_lead extends LightningElement {
objectApiName = LEAD_OBJECT;
fields = [FIRST_NAME, LAST_NAME, PHONE,COMPANY];
handleSuccess(event) {
const toastEvent = new ShowToastEvent({
title: "Lead created",
message: "Record ID: " + event.detail.id,
variant: "success"
});
this.dispatchEvent(toastEvent);
}
}
lightning-record-edit-form
This component helps you to create a new Salesforce record or edit an existing one. Similar to lightning-record-form, the object-api-name
attribute is required here as well. The record-id
attribute is required only when editing an existing record. To specify the fields included in the form, use lighting-input-field
components. It also uses a button for form submission. For more details, refer this link.
The above example for the new lead create form is updated to use lightning-record-edit-form
, as shown below.
<template>
<lightning-card title = "Lead Create Form">
<lightning-record-edit-form object-api-name={objectApiName}>
<lightning-input-field field-name={firstName}> </lightning-input-field>
<lightning-input-field field-name={lastName}> </lightning-input-field>
<lightning-input-field field-name={phone}> </lightning-input-field>
<lightning-input-field field-name={company}> </lightning-input-field>
<lightning-button variant="brand" type="submit" label="Save">
</lightning-button>
</lightning-record-edit-form>
</lightning-card>
</template>
lightning-record-view-form
This component helps you to view an existing record for specified fields associated with that record. Both object-api-name
and record-id
attribute are required in this component. To specify the fields included in the form, use lighting-output-field
components. For more details, refer to this link.
Benefits of Using Base Components
- Most of the Salesforce record display needs can be met using these form components without much Javascript.
- These base components provide automatic field mapping with field-level validation.
2. Read Data and Metadata With LDS
To read data and metadata from Salesforce without using Apex, you can leverage Lightning Data Service (LDS). LDS provides adapters that work with the wire service to fulfill this purpose. These adapters can be used to read both lists of records and object or layout schemas.
To implement this, LDS provides adapters that can be imported into your LWC and wired to a property or function using the wire service. Below is the syntax:
// Syntax
import { adapterMethod } from 'adapterModule';
@wire(adapterMethod, adapterConfig)
propertyOrFunction;
A list of currently available wire adapters can be found here.
Let us look at the two commonly used wire adaptors in detail: lightning/uiObjectInfoApi
and lightning/uiRecordApi
.
lightning/uiObjectInfoApi
This adaptor is used to get object metadata. The following methods are available to use with this adaptor:
getObjectInfo
for getting an object's metadata.getPicklistValues
for getting values of a picklist field.
Here is a simple implementation code to fetch and display the lead's industry picklist field using LDS wire adaptors.
import { LightningElement,wire } from 'lwc';
import LEAD_OBJECT from "@salesforce/schema/Lead";
import { getPicklistValues, getObjectInfo } from "lightning/uiObjectInfoApi";
import INDUSTRY_FIELD from "@salesforce/schema/Lead.Industry";
export default class Lds_wire_adaptor_test extends LightningElement {
leadIndustryValues;
@wire(getObjectInfo, { objectApiName: LEAD_OBJECT })
leadObjectInfo;
@wire(getPicklistValues, { recordTypeId: "$leadObjectInfo.data.defaultRecordTypeId", fieldApiName: INDUSTRY_FIELD })
picklistResults({ error, data }) {
if (data) {
this.leadIndustryValues = JSON.stringify(data.values);
this.error = undefined;
} else if (error) {
this.error = error;
this.leadIndustryValues = undefined;
}
}
}
lightning/uiRecordApi
This adaptor is used to get record values. The following methods are available to use with this adaptor.
getRecord
to get the record's data. If you want a list of records, you can usegetRecords
.getFieldValue
gets a field's value from a record.
Here is a simple use case to pull the logged-in user's username using getRecord
and getFieldValue
.
import { LightningElement,wire,track } from 'lwc';
import USER_ID from "@salesforce/user/Id";
import { getRecord, getFieldValue } from "lightning/uiRecordApi";
import USER_NAME from "@salesforce/schema/User.Username";
export default class Lds_getRecord extends LightningElement {
@track loggedInUserId = USER_ID;
userName;
@wire(getRecord, { recordId: "$loggedInUserId", fields: [USER_NAME] })
wiredUser({ error, data }) {
if (error) {
console.log('error');
} else if (data) {
this.userName = getFieldValue(data, USER_NAME);
}
}
}
Benefits of Using LDS Wire Adaptors
- The wire properties become reactive properties, meaning the component's DOM will automatically be refreshed when the property value changes.
- LDS wire adaptors offer a client-side cache, which improves performance.
3. Creating, Updating, and Deleting Data Using LDS
We can create, update, and delete data using LDS without needing the @wire decorator
. Instead, we call the wire functions imperatively.
The lightning/uiRecordApi
wire adaptor has the following methods to modify data:
createRecord
for creating a recordupdateRecord
for updating a recorddeleteRecord
for deleting a record
Let us look at an example. Below is how we can re-write the lead form from the beginning of this article using the createRecord
method.
import { LightningElement } from 'lwc';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
import { createRecord } from 'lightning/uiRecordApi';
import LEAD_OBJECT from '@salesforce/schema/Lead';
export default class Lds_wire_adaptor_create_lead extends LightningElement {
objectApiName = LEAD_OBJECT.objectApiName;
firstName;
lastName;
phone;
company;
leadId;
handleFirstNameChange(event) {
this.firstName = event.target.value;
}
handleLastNameChange(event) {
this.lastName = event.target.value;
}
handlePhoneChange(event) {
this.phone = event.target.value;
}
handleCompanyChange(event) {
this.company = event.target.value;
}
async createLead(){
let leadRecord = {};
leadRecord.FirstName = this.firstName;
leadRecord.LastName = this.lastName;
leadRecord.Phone = this.phone;
leadRecord.Company = this.company;
const fields = leadRecord;
console.log('fields',fields);
const recordInput = { apiName: this.objectApiName, fields };
try {
const lead = await createRecord(recordInput);
this.leadId = lead.id;
console.log('did we enter here ',this.leadId);
this.dispatchEvent(
new ShowToastEvent({
title: 'Success',
message: 'Lead created',
variant: 'success'
})
);
} catch (error) {
console.log('did we enter here in error');
this.dispatchEvent(
new ShowToastEvent({
title: 'Error creating record',
message: 'Error Creating Lead',
variant: 'error'
})
);
}
}
}
Benefits of Using LDS Wire Adaptors
- In addition to modifying records, wire functions also update the LDS cache, which is shared by other components using the same record, ensuring data synchronization across all components.
- LDS respects Salesforce's built-in security features, such as sharing settings, field-level security, and CRUD settings.
Conclusion
Lightning Data Service is a powerful tool that enhances speed and efficiency when working with data in Lightning Web Components. When used effectively, its features can save development time, deliver high-performance components, ensure data consistency and security, and ultimately improve the user experience.
Opinions expressed by DZone contributors are their own.
Comments