Thursday, February 18, 2021

lightning/uiRecordApi and How to use getRecord in LWC?

lightning/uiRecordApi provided by Salesforce is a set of JavaScript APIs that allows you to perform CRUD (Create, Read, Update, Delete) operations on Salesforce records using Lightning Web Components (LWC). 

Using lightning/uiRecordApi we can perform operations as mentioned below without using Apex.

1) Create a record 

2) Get record data

3) Delete a record

4) Get a field value from record

5) Update a record 

6) Refresh record

  • Access Salesforce data without apex.
  • Handles field-level security and sharing rules.
  • Efficiently caches data to optimize performance.
  • Syntax to import this API:

    import { getRecord, createRecord, updateRecord, deleteRecord } from 'lightning/uiRecordApi';

    In this blog post we will learn "How to get record data in lightning/uiRecordApi using getRecord"?

    Let's understand with simple example as explained below:

    getRecordLWCExample.html

    <template >

        <template if:true={contactData}>

         Contact Name : {contactName} <br/>

         Contact Phone  : {contactPhone}

        </template>

    </template>


    getRecordLWCExample.js

    import { LightningElement, api, wire, track } from 'lwc';

    import { getRecord } from 'lightning/uiRecordApi';

    const FIELDS = ['Contact.Name', 'Contact.Phone'];

    export default class GetRecordLWCExample extends LightningElement {

        @api recordId;

        contactData;

        contactName;

        contactPhone;

        @wire(getRecord, { recordId: '$recordId', fields: FIELDS, modes : ['View', 'Edit', 'Create']})

        wiredRecord({ error, data }) {

            if (error) {

                 console.log('Received Error');

            } else if (data) {

                console.log('data is'+data);

                

                this.contactData = data;

                this.contactName =   this.contactData.fields.Name.value;

                this.contactPhone =  this.contactData.fields.Phone.value;

                console.log('contact Name is'+this.contactName);

                console.log('contact Phone is'+this.contactPhone);

                

            }

        }

    }


    getRecordLWCExample.js-meta.xml


    <?xml version="1.0" encoding="UTF-8"?>

    <LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">

        <apiVersion>50.0</apiVersion>

        <isExposed>true</isExposed>

        <targets>

     

            <target>lightning__RecordPage</target>

     

        </targets>

    </LightningComponentBundle>


    Add the above component to contact page as shown below,


    How to use getRecord in lightning/uiRecordApi?

    No comments:

    Post a Comment