Get Record in LWC using getRecord of uiRecordApi

In this post, we will implement the functionality to Get Record in LWC using getRecord of uiRecordApi module with the Wire Service. In the previous post, we implemented the functionality to create a record using createRecord of uiRecordApi module which you can check here.

Let’s just hop into the implementation.

Implementation

In this implementation, we will create an Account record using createRecord() Lightning Data Service. We will use the Id of this Account and fetch the Account using getRecord adapter of Wire Service. As soon as the Account is created, we will fetch the Account details and display the Account Name, Id, Account Number, Phone of Account on UI. This implementation will focus on getting a record rather than creating a record, though it will contain all the code for creating records as well. If you want to check in detail how we can create a record using Lightning Data Service, you may want to visit the post here.

First, create a component ldsCreateRecord. Add the markup to fetch Account Name, Account Number, and Phone from User. Add a section to display the created record as well. In this implementation, we are displaying the Account field values with lightning-formatted-text using Getters. Check this post if you want to see how Getters works in Lightning Web Component.

ldsCreateRecord.html

<template>
    <lightning-card title="Create Account Record using LDS">
        <lightning-layout>
            <lightning-layout-item size="6">
                <!-- Displaying fields to get information. -->
                <lightning-input class="slds-p-around_medium" label="Name" name="accoutName" 
                    onchange={nameChangedHandler}></lightning-input>
                <lightning-input class="slds-p-around_medium" label="Account Number" name="accoutNumber" 
                    onchange={numberChangedHandler}></lightning-input>
                <lightning-input class="slds-p-around_medium" label="Phone" type="phone" name="accountPhone" 
                    onchange={phoneChangedHandler}></lightning-input>
                <br/>
                <lightning-button class="slds-m-left_x-small" label="Create Account" variant="brand" 
                    onclick={createAccount}></lightning-button>
            </lightning-layout-item>
            <lightning-layout-item size="6">
                <p class="slds-text-heading_small">Latest Account Details</p>
                
                <!-- Displaying Account Information. -->
                <div class="slds-p-left_medium">
                    <p><lightning-formatted-text value={accountName}></lightning-formatted-text></p>
                    <p><lightning-formatted-text value={accountId}></lightning-formatted-text></p>
                    <p><lightning-formatted-text value={accountNumber}></lightning-formatted-text></p>
                    <p><lightning-formatted-text value={accountPhone}></lightning-formatted-text></p>
                </div>
            </lightning-layout-item>
        </lightning-layout>
    </lightning-card>
</template>

After clicking the Create Account button, createAccount() is called to create the Account. Once the Account record is created successfully, we get the Id of Account from the response in recordId property.

In the JS controller, Import the getRecord from lightning/uiRecordApi module. Create Array arrFields and put all the fields that we want to query.

getRecord Wire Adapter

Create a Wire property accountRecord with getRecord adapter and pass recordId and fields as a configuration parameter for this Wire Service. Take a look at below Wire property:

@wire(getRecord, {recordId:'$idAccount', fields: arrFields})
accountRecord;

Here, the wire is the decorator for the property accountRecord. The first parameter is getRecord which is the Adapter Id that tells the Wire service to fetch the record. The second parameter is the Configuration object which has two parameters, recordId, and fields. We are passing idAccount as recordId which is the Id of Account that is created when we click the Create Account button. We can assign this.idAccount to recordId but Wire service won’t fetch the different Account if idAccount is changed. Hence, we need to assign $idAccount to recordId to make it dynamic so that if idAccount is updated, Wire service will fetch the respective Account. The second parameter is fields that have an array of fields to query.

Wire properties are reactive by default. Hence as soon as the Account is fetched in accountRecord, it will reflect on UI.

If you want to know more about Wire service, check the official documentation of Salesforce here.

ldsCreateRecord.js

import { LightningElement, track, wire } from 'lwc';
import { createRecord, getRecord } from 'lightning/uiRecordApi';
const arrFields = ['Account.Id', 'Account.Name', 'Account.Phone', 'Account.AccountNumber'];
export default class LdsCreateRecord extends LightningElement {
    strName;
    strAccountNumber;
    strPhone;
    idAccount;
    @wire(getRecord, {recordId:'$idAccount', fields: arrFields})
    accountRecord;
    // Change Handlers.
    nameChangedHandler(event){
        this.strName = event.target.value;
    }
    numberChangedHandler(event){
        this.strAccountNumber = event.target.value;
    }
    phoneChangedHandler(event){
        this.strPhone = event.target.value;
    }
    // Insert record.
    createAccount(){
        // Creating mapping of fields of Account with values
        var fields = {'Name' : this.strName, 'AccountNumber' : this.strAccountNumber, 'Phone' : this.strPhone};
        // Record details to pass to create method with api name of Object.
        var objRecordInput = {'apiName' : 'Account', fields};
        // LDS method to create record.
        createRecord(objRecordInput).then(response => {
            this.idAccount = response.id;
        }).catch(error => {
            alert('Error: ' +JSON.stringify(error));
        });
    }
    //Getters
    get accountName(){
        if(this.accountRecord.data){
            return this.accountRecord.data.fields.Name.value;
        }
        return undefined;
    }
    get accountPhone(){
        if(this.accountRecord.data){
            return this.accountRecord.data.fields.Phone.value;
        }
        return undefined;
    }
    get accountNumber(){
        if(this.accountRecord.data){
            return this.accountRecord.data.fields.AccountNumber.value;
        }
        return undefined;
    }
    get accountId(){
        if(this.accountRecord.data){
            return this.accountRecord.data.fields.Id.value;
        }
        return undefined;
    }
}

Get Record in LWC using getRecord of uiRecordApi

After this implementation, this is how our output looks:

Get Record in LWC using getRecord of uiRecordApi
Get Record in LWC using getRecord of uiRecordApi

Also Read:

This is how we can Get Record in LWC using getRecord of uiRecordApi module with the help of Wire Service.

In the next post, we will implement lightning-record-view-form and lightning-record-edit-form of Lightning Data Service. If you don’t want to miss new posts, please Subscribe here. See you in the next post.

Leave a Comment