Introduction
Lightning Data Service (LDS) is a powerful tool in Salesforce’s Lightning Web Components (LWC) framework that simplifies working with Salesforce data.
It enables components to access, create, update, or delete Salesforce records without writing Apex code, leveraging the Lightning Data Service to manage data efficiently and ensure consistency across components.
In this blog, we’ll dive into the key concepts of LDS, its benefits, and practical examples of its usage in LWC.
What is Lightning Data Service (LDS)?
Lightning Data Service (LDS) is Salesforce’s mechanism for managing and sharing record data between Lightning components. It uses Salesforce’s native data caching layer to:
- Avoid redundant server calls.
- Automatically handle field-level security and sharing rules.
- Maintain consistency when multiple components access the same data.
Benefits of Using LDS
- No Apex Code Required: Fetch, modify, and save data without writing any server-side code.
- Automatic CRUD Operations: Supports create, read, update, and delete (CRUD) operations.
- Handles Security: Automatically respects sharing rules and field-level security.
- Efficient Caching: Reduces the number of server calls by caching records.
- Real-Time Updates: Synchronizes data between components when the same record changes.
Core Features of LDS
- Declarative Record Access: Fetch and display Salesforce records with ease.
- CRUD Operations: Perform Create, Read, Update, and Delete actions.
- Automatic Data Refresh: If a record changes elsewhere, LDS updates the component automatically.
- Error Handling: LDS provides standardised error messages for smoother debugging.
How to Use LDS in LWC
LDS provides two primary approaches for working with records:
1. Using Base Lightning Components
These pre-built components provide the quickest way to implement common record operations
- lightning-record-form : It is the Quickest way to display/edit records.
- lightning-record-view-form : When you need a read-only display.
- lightning-record-edit-form : When you need full control over the edit form.
2. Using Wire Adapters for Custom Implementations
For more complex scenarios, LDS provides direct wire adapters:
- getRecord
- getRecordCreateDefaults
Let’s explore each approach with examples.
Example 1: Display a Record Using 'lightning-record-form'
The easiest way to display a record is by using the lightning-record-form component. It requires minimal code.
Html
object-api-name="Contact"
layout-type="Full"
mode="view">
Explanation:
- record-id: The ID of the record to fetch.
- object-api-name: The object the record belongs to (e.g., Contact, Account).
- layout-type: Controls the form layout (Compact or Full).
- mode: Determines the mode (view, edit, or readonly).
Example 2: Custom Record Display Using 'lightning-record-view-form'
Purpose: Read-only record display
Features:
Customizable field layout
Respects field-level security
Example 3: Using 'lightning-record-edit-form'
For creating and editing records, <lightning-record-edit-form> offers a declarative way to handle form submissions.
Example 1: Creating a Record
Explanation:
The lightning-record-edit-form automatically handles record creation, including validation and saving data to Salesforce.
- lightning-record-edit-form: Enables inline editing.
- lightning-messages: Displays system messages like validation errors.
- lightning-input-field: Allows editing of specific fields.
Example 2: Editing a Record
Html:
Explanation:
This form fetches the account record, displays its fields for editing, and handles updates when the form is submitted.
- lightning-record-edit-form: Enables inline editing.
- lightning-messages: Displays system messages like validation errors.
- lightning-input-field: Allows editing of specific fields.
4. Using @wire to Fetch Data Programmatically
LWC provides @wire to declaratively fetch data using Lightning Data Service. Common wire adapters include:
- getRecord: Fetch a single record.
- getRecordUi: Fetch a record along with metadata.
- getObjectInfo: Fetch metadata for an object.
Example: Fetching a Single Record
Javascript:
// accountRecord.js
import { LightningElement, wire } from 'lwc';
import { getRecord } from 'lightning/uiRecordApi';
const FIELDS = ['Account.Name', 'Account.Phone', 'Account.Industry'];
export default class AccountRecord extends LightningElement {
recordId = '001XXXXXXXXXXXXXXX'; // Example Record ID
@wire(getRecord, { recordId: '$recordId', fields: FIELDS })
account;
get accountName() {
return this.account.data ? this.account.data.fields.Name.value : 'N/A';
}
get accountPhone() {
return this.account.data ? this.account.data.fields.Phone.value : 'N/A';
}
get accountIndustry() {
return this.account.data ? this.account.data.fields.Industry.value : 'N/A';
}
}
Html
Account Name: {accountName}
Phone: {accountPhone}
Industry: {accountIndustry}
Explanation:
The getRecord adapter fetches the account record and provides reactive data to the component.
Example: Fetching Object Metadata
Javascript:
// objectMetadata.js
import { LightningElement, wire } from 'lwc';
import { getObjectInfo } from 'lightning/uiObjectInfoApi';
import ACCOUNT_OBJECT from '@salesforce/schema/Account';
export default class ObjectMetadata extends LightningElement {
@wire(getObjectInfo, { objectApiName: ACCOUNT_OBJECT })
accountMetadata;
get accountLabel() {
return this.accountMetadata.data
? this.accountMetadata.data.label
: 'N/A';
}
get accountFields() {
return this.accountMetadata.data
? Object.keys(this.accountMetadata.data.fields).join(', ')
: 'No fields available';
}
}
Html
Object Label: {accountLabel}
Fields: {accountFields}
Key LDS Adapters:
Use of different LDS Adapters
- getRecord : Fetch a record.
- getRecordCreateDefaults : Get default values for a new record.
- createRecord : Create a new record.
- updateRecord : Update an existing record.
- deleteRecord : Delete a record.
LDS vs. Apex: When to Use Which?
Feature | LDS | Apex |
---|---|---|
Basic CRUD | ✅ Best | ⚠ Overkill |
Complex Logic | ❌ No | ✅ Required |
Performance | ✅ Optimized | Depends |
Auto-Caching | ✅ Yes | ❌ No |
Record Access | ✅ FLS Aware | ✅ (With sharing) |
When to Use LDS?
Simple record operations
When you need automatic UI updates
To reduce Apex dependency
When to use Apex ?
Complex validation rules
Transactional operations (multiple records)
When needing SOQL/SOSL queries
Comparison: Wire Adapters vs. Record Edit Forms
Feature | LDS Wire Adapters (getRecord , updateRecord ) | Record Edit Forms (lightning-record-edit-form ) |
---|---|---|
Implementation | JavaScript code (imperative) | Declarative HTML markup |
Control Level | High (full programmatic control) | Medium (pre-built with customization options) |
Best For | Custom UIs, complex logic | Standard forms, rapid development |
Data Handling | Manual field management | Automatic field rendering |
Error Handling | Manual implementation | Built-in basic handling |
Code Volume | High (~20-30 lines) | Low (~5-10 lines) |
Performance | Optimized (fetch only needed data) | Good (may load full layout) |
Validation | Custom validation possible | Basic field-level validation |
UI Flexibility | Complete freedom | Limited to component’s design |
Learning Curve | Steeper (requires JS knowledge) | Easier (mostly configuration) |
Use Case Example | Dashboard components, complex editors | Standard object edit pages |
Rule of Thumb:
- Use Record Forms for 80% of standard CRUD operations
- Use Wire Adapters when you need custom behavior or complex logics
Best Practices for Using LDS
- Use LDS Whenever Possible: Avoid writing custom Apex unless required for complex business logic.
- Avoid Redundant Queries: Use the same @wire adapter across components to leverage LDS caching.
- Leverage Error Handling: Handle errors gracefully when using wire adapters or record-edit forms.
- Respect Security: LDS ensures that field-level security and sharing rules are respected, but double-check access permissions for your component.
Conclusion
Lightning Data Service (LDS) makes working with Salesforce data in LWC straightforward and efficient.
By using @wire and <lightning-record-edit-form>, developers can interact with Salesforce data declaratively, reduce code complexity, and ensure security and consistency.
With its caching mechanism and real-time updates, LDS is a must-know for Salesforce developers who want to build scalable and high-performance applications.