Lightning web Component updateRecord Example

Let us discuss here how to use lightning/uiRecordApi module adapters. This module includes wire adapters to record data and get default values to create records. It also includes JavaScript APIs to create, delete, update, and refresh records. one of the most of importance function is updateRecord that will be used to update the record in the database without using apex class.

Syntax 

the updateRecord syntax looks like below

import { updateRecord } from 'lightning/uiRecordApi';
updateRecord(recordInput: Record, clientOptions: Object): Promise<Record>
  • recordInput— (Required) A RecordInput object used to update the record. To create the object, call generateRecordInputForUpdate(record).
  • clientOptions— (Optional) To check for conflicts before you update a record, pass const clientOptions = {'ifUnmodifiedSince' : lastModifiedDate}. Get lastModifiedDate via a wire service adapter that returns a record object: const lastModifiedDate = record.fields.LastModifiedDate.value;.
  • A Promise object that resolves with the updated record. The record contains data for the fields in the record layout.

Create a Lightning Web component

create a new lightning web component using this SFDX command

sfdx force:lightning:component:create --type lwc -n updaterecord -d force-app/main/default/lwc

use this updaterecord.html code

<template>
    <lightning-card title="Update  Account Record" icon-name="standard:record">
        <div class="slds-m-around_medium">
            <lightning-input label="Name" onchange={handleNameChange} class="slds-m-bottom_x-small"></lightning-input>
            <lightning-input label="Annual Revenue" type="number" onchange={handleNameChange} class="slds-m-bottom_x-small"></lightning-input>

            <lightning-input label="Phone" type="phone" onchange={handleNameChange} class="slds-m-bottom_x-small"></lightning-input>
            <lightning-input label="Fax" type="phone" onchange={handleNameChange} class="slds-m-bottom_x-small"></lightning-input>

            <lightning-button label="Update  Account" variant="brand" onclick={updateAccount}></lightning-button>
        </div>
    </lightning-card>
</template>

Use this updaterecord .js code

import {
LightningElement,
track,api,wire
} from 'lwc';
import {
ShowToastEvent
} from 'lightning/platformShowToastEvent';
import ACCOUNT_OBJECT from '@salesforce/schema/Account';
import NAME_FIELD from '@salesforce/schema/Account.Name';
import ID_FIELD from '@salesforce/schema/Account.ID';

import ANNUALREV_FIELD from '@salesforce/schema/Account.AnnualRevenue';
import Fax_FIELD from '@salesforce/schema/Account.Fax';
import PHONE_FIELD from '@salesforce/schema/Account.Phone';


import {
getRecord,
updateRecord,
generateRecordInputForUpdate,
getFieldValue,
} from 'lightning/uiRecordApi';
import {
CurrentPageReference
} from 'lightning/navigation';


export default class Updaterecord extends LightningElement {
@api recordId;
@track accountId;
@track name = 'Demo Account';
@track annualrev = 0;
@track fax = '1231234345345';
@track phone = '1231234345345';

handleNameChange(event) {
    this.accountId = undefined;
    console.log('label values --->>' + event.target.label);
    if (event.target.label === 'Name') {
        this.name = event.target.value;
    }
    if (event.target.label === 'Annual Revenue') {
        this.annualrev = event.target.value;
    }
    if (event.target.label === 'Fax') {
        this.fax = event.target.value;
    }
    if (event.target.label === 'Phone') {
        this.phone = event.target.value;
    }

}


updateAccount() {
    let record = {
        fields: {
            Id: this.recordId,
            Name: this.name,
            AnnualRevenue:this.annualrev ,
            Fax:this.fax ,
            Phone:this.phone,
        },
    };
    updateRecord(record)
        // eslint-disable-next-line no-unused-vars
        .then(() => {
            this.dispatchEvent(
                new ShowToastEvent({
                    title: 'Success',
                    message: 'Record Is Updated',
                    variant: 'sucess',
                }),
            );
        })
        .catch(error => {
            this.dispatchEvent(
                new ShowToastEvent({
                    title: 'Error on data save',
                    message: error.message.body,
                    variant: 'error',
                }),
            );
        });


}

}

use this updaterecord.js-meta.xml

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata" fqn="helloWorld">
    <apiVersion>45.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
        <target>lightning__RecordPage</target>
    </targets>
</LightningComponentBundle>

 

Push changes to scratch org.

Push changes to scratch using this command and add this component to record page using lighting app builder

sfdx force:source:push

 

Understand  the code

The following JavaScript code will update the tracked properties when an input value is changed

handleNameChange(event) {
    this.accountId = undefined;
    console.log('label values --->>' + event.target.label);
    if (event.target.label === 'Name') {
        this.name = event.target.value;
    }
    if (event.target.label === 'Annual Revenue') {
        this.annualrev = event.target.value;
    }
    if (event.target.label === 'Fax') {
        this.fax = event.target.value;
    }
    if (event.target.label === 'Phone') {
        this.phone = event.target.value;
    }

}

The following code will call from the update button  which contains the record details for the update using the updateRecord function

updateAccount() {
    let record = {
        fields: {
            Id: this.recordId,
            Name: this.name,
            AnnualRevenue:this.annualrev ,
            Fax:this.fax ,
            Phone:this.phone,
        },
    };
    updateRecord(record)
        // eslint-disable-next-line no-unused-vars
        .then(() => {
            this.dispatchEvent(
                new ShowToastEvent({
                    title: 'Success',
                    message: 'Record Is Updated',
                    variant: 'sucess',
                }),
            );
        })
        .catch(error => {
            this.dispatchEvent(
                new ShowToastEvent({
                    title: 'Error on data save',
                    message: error.message.body,
                    variant: 'error',
                }),
            );
        });


}