Update Salesforce Records Using LWC and lightning/uiRecordApi Without Apex

In Salesforce, you often need to update records directly from a Lightning Web Component (LWC). Traditionally, this might involve writing Apex methods, but with the lightning/uiRecordApi, you can update records directly without writing any Apex logic. This post will guide you through the process step by step.

Introduction

The lightning/uiRecordApi module in Salesforce provides a simple way to interact with Salesforce records. This API allows you to create, read, update, and delete records without needing to write any custom Apex code. Today, we’ll focus on how to update records using the updateRecord method, which is perfect for scenarios where you need to modify a record directly from your LWC component.

Step-by-Step Guide

Here i am updating account record from contact record detail page. First, you’ll need to create an LWC component. If you haven’t already, create a new component

updateRecordWithoutApex.html

<template>
    <lightning-card variant="Narrow" title="Update Record Without Apex" icon-name="standard:account">
        <div class="slds-m-around_medium">
            <lightning-layout>
                <lightning-layout-item flexibility="auto" padding="around-small">
                    <lightning-input type="text" value={name} variant="standard" name="name" label="Account Name"
                        onchange={handlechange}>
                    </lightning-input>
                </lightning-layout-item>
                <lightning-layout-item flexibility="auto" padding="around-small">
                    <lightning-input type="text" value={phone} onchange={handlechange} variant="standard" name="phone"
                        label="Account Phone">
                    </lightning-input>
                </lightning-layout-item>
            </lightning-layout>
            <br>
            <lightning-button variant="brand" label="Update" title="Update" onclick={handleClick}></lightning-button>
        </div>
    </lightning-card>
</template>

updateRecordWithoutApex.js

import { LightningElement, api, wire, track } from 'lwc';
import { getRecord } from 'lightning/uiRecordApi';
import { updateRecord } from 'lightning/uiRecordApi';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
const FIELDS = ['Contact.Account.Name', 'Contact.Account.Phone', 'Contact.AccountId']
export default class UpdateRecordWithoutApex extends LightningElement {
    @api recordId;
    @track accountId;
    @track name;
    @track phone;
    @wire(getRecord, { recordId: '$recordId', fields: FIELDS })
    wiredRecord({ error, data }) {
        if (error) {
            this.showToastEvent('Error fetching record', error.body.message, 'error');
        } else if (data) {
            this.accountId = data.fields.AccountId.value;;
            this.name = data.fields.Account.value.fields.Name.value;
            this.phone = data.fields.Account.value.fields.Phone.value;
        }
    }
    handlechange(event) {
        if (event.target.name === 'name') {
            this.name = event.target.value;
        } else {
            this.phone = event.target.value;
        }
    }
    handleClick() {
        const fields = {
            Id: this.accountId,
            Name: this.name,
            Phone: this.phone
        };
        const recordInput = { fields };
        updateRecord(recordInput)
            .then(() => {
                this.showToastEvent('Success', 'Account updated ' + this.name, 'success');
            })
            .catch(error => {
                this.showToastEvent('Error updating record', error.body.message, 'error');
            });
    }
    showToastEvent(title, message, variant) {
        this.dispatchEvent(
            new ShowToastEvent({
                title: title,
                message: message,
                variant: variant
            })
        );
    }
}

updateRecordWithoutApex.js-meta.xml

<?xml version="1.0"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
	<apiVersion>60.0</apiVersion>
	<isExposed>true</isExposed>
	<targets>
		<target>lightning__RecordPage</target>
	</targets>
</LightningComponentBundle>

Handle Success and Error Scenarios

The ShowToastEvent is used to display a toast notification for both success and error scenarios. You can customize the messages and variants as needed.

Conclusion

By following these steps, you can update records directly from your LWC component without the need for Apex. This method simplifies your code and leverages Salesforce’s built-in APIs to interact with records efficiently. The lightning/uiRecordApi is a powerful tool for developers who want to streamline record operations in LWC.

Output

References

Spread the love
Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *