Current Record Id

How to Get Current Record Id in Lightning Web Component | Salesforce Developer Guide

Getting record in Lightning Aura Component is quite easy, we use force:hasRecordId and get the result in controller by using, 

getRecordId:function(component,event, helper){
    var currentRecordId =  component.get(“v.recordId”);
    console.log(‘currentRecordId ‘+currentRecordId );
}

It is all good in Lightning Aura Components, but if you are starting a new Lightning Web Component, how can you get the recordId?

Create a new Lightning Web Component, and name it as recordIdInLWC. When the component is created, go to its .js file.

import { LightningElement, api } from 'lwc';
export default class RecordIdInLWC extends LightningElement {
}
//Inside export part introduced a variable for recordId by using @api decorator. It will be a public access modifier.
import { LightningElement, api } from 'lwc';
export default class RecordIdInLWC extends LightningElement {
    //Create a Record ID variable
    @api recordId; 
}

dont miss out iconDon't forget to check out: Salesforce Lightning Component Inside Lightning Web Component Using Visualforce Page

Now, go to the components:

HTML file

<template>
    <div >
        <lightning-record-view-form record-id={recordId} object-api-name="Contact">
            <div >
                <div >
                    <lightning-output-field field-name="Name"></lightning-output-field>                    
                </div>
                <div >
                    <lightning-output-field field-name="Phone"></lightning-output-field>
                    <lightning-output-field field-name="Email"></lightning-output-field>
                </div>
            </div>
        </lightning-record-view-form>
    </div>
</template>

.js File

import { LightningElement,api } from 'lwc'; 
export default class RecordIdInLWC extends LightningElement {
    @api recordId;
}

XML File

<?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>

dont miss out iconCheck out another amazing blog by Krati here: What are Quote Line Items in Salesforce

Add this component to Contact Detail Page

  • Go to the Contact tab.
  • Open any contact record.
  • Click Setup (Gear Icon) and select Edit Page.
  • Under Custom Components, find your recordIdExampleLWC component and drag it on the right-hand side top.

Click Save and activate.

Responses

Popular Salesforce Blogs