Lightning Web Component wired updateRecord example

uiRecordApi-updateRecord-example-with-lwc

Hello Trailblazers! In this post, we will see how to update a record using the updateRecord method from uiRecordApi of Lightning web components.

We will create a simple form to update account fields using updateRecord method. I have also used the getRecord to get the record, @api recordId is also defined in the component so we can get record id when the component is added on the record home page.

The updateRecord method takes two parameters.

  • recordInput (required) - this is the object where you put all the fields that you want to update on the record. You need to put the data in the below format. 

    { 
        fields : {
            Id: '',
            Name: '',
            // ...
        }
    }


    Also please note that the Id is required to update the record.

  • clientOptions (optional) - This is option is used to check the conflicts before updating the record, you need to pass the LastModifiedDate in the below format.

    {
        'ifUnmodifiedSince': 'lastModifiedDate'
    }
    


Sample Code


updateRecordExample.js


import { LightningElement, api, wire } from "lwc";
import { getRecord, updateRecord, getFieldValue } from "lightning/uiRecordApi";
import { ShowToastEvent } from "lightning/platformShowToastEvent";

// import schemas
import NAME from "@salesforce/schema/Account.Name";
import PHONE from "@salesforce/schema/Account.Phone";
import WEBSITE from "@salesforce/schema/Account.Website";
export default class UpdateRecordExample extends LightningElement {
    @api recordId;
    disabled;

    @wire(getRecord, { recordId: "$recordId", fields: [NAME, PHONE, WEBSITE] })
    account;

    get name() {
        return getFieldValue(this.account.data, NAME);
    }

    get phone() {
        return getFieldValue(this.account.data, PHONE);
    }

    get website() {
        return getFieldValue(this.account.data, WEBSITE);
    }

    handleChange(event) {
        if (!event.target.value) {
            event.target.reportValidity();
            this.disabled = true;
        } else {
            this.disabled = false;
        }
    }

    updateAccount() {
        // validate the inputs
        const allValid = [
            ...this.template.querySelectorAll("lightning-input")
        ].reduce((validSoFar, inputFields) => {
            inputFields.reportValidity();
            return validSoFar && inputFields.checkValidity();
        }, true);

        if (allValid) {
            // Create the recordInput object
            const fields = {};
            fields.Id = this.account.data.id;
            fields[NAME.fieldApiName] = this.template.querySelector(
                "[data-field='Name']"
            ).value;
            fields[PHONE.fieldApiName] = this.template.querySelector(
                "[data-field='Phone']"
            ).value;
            fields[WEBSITE.fieldApiName] = this.template.querySelector(
                "[data-field='Website']"
            ).value;

            const recordInput = { fields };

            updateRecord(recordInput)
                .then(() => {
                    this.dispatchEvent(
                        new ShowToastEvent({
                            title: "Success",
                            message: "Account updated",
                            variant: "success"
                        })
                    );
                })
                .catch((error) => {
                    this.dispatchEvent(
                        new ShowToastEvent({
                            title: "Error updating account",
                            message: error.body.message,
                            variant: "error"
                        })
                    );
                });
        } else {
            // The form is not valid
            this.dispatchEvent(
                new ShowToastEvent({
                    title: "Something is wrong",
                    message: "Check your input and try again.",
                    variant: "error"
                })
            );
        }
    }
}

updateRecordExample.html


<template>
    <lightning-card title="Update Record Example" icon-name="standard:account">
        <div class="slds-m-around_medium">

            <template if:true={account.data}>
                <lightning-input
                    label="Account Name"
                    value={name}
                    data-field="Name"
                    onchange={handleChange}
                    class="slds-m-bottom_x-small"
                    required>
                </lightning-input>

                <lightning-input 
                    label="Phone"
                    type="phone"
                    value={phone}
                    data-field="Phone"
                    onchange={handleChange}
                    class="slds-m-bottom_x-small"
                    required>
                </lightning-input>

                <lightning-input 
                    label="Website"
                    type="url"
                    value={website}
                    data-field="Website"
                    onchange={handleChange}
                    class="slds-m-bottom_x-small"
                    required>
                </lightning-input>

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

            </template>

            <template if:true={account.error}>
                Error loading account.
            </template>

            {data}
        </div>
    </lightning-card>
</template>

updateRecordExample.js-meta.xml


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


LWC Series

I am writing a complete tutorial for LWC beginners, check out my all posts about it.

  1. Lightning Web Components Folder Structure
  2. Lightning data service with LWC
  3. All methods from uiRecordApi LWC
  4. Lightning Web Component createRecord example
  5. All posts from LWC series
No comments :
Post a Comment

Hi there, comments on this site are moderated, you might need to wait until your comment is published. Spam and promotions will be deleted. Sorry for the inconvenience but we have moderated the comments for the safety of this website users. If you have any concern, or if you are not able to comment for some reason, email us at rahul@forcetrails.com