HOW TO GET OBJECT API NAME AND RECORD ID IN LWC ♨️

 



How to get Object Api Name and Record Id in LWC

Use Case - Dario has a Lightning Web Component which is calling an http callout method from apex. From LWC he is sending Object Api Name and RecordId to the apex callout method.

He has an action button on LEAD, ACCOUNT and CONTACT object record page on which he is calling that Lightning Web Component.

Because that is a common LWC component for all the 3 objects, he needs to get the object api name and record id of the record page which triggers the action button.

GET RECORD ID -

For getting the record id from a lightning record details page we will create a public property "recordId" and declare it with @api decorator.

 @api recordId;

Once you create a public property "recordId", you will get the 18-characters record id in this variable.

GET OBJECT API NAME -

Same as getting the recordId you can get the object's api name of the lightning record page by creating a public property "objectApiName" and declaring it with @api decorator.

  @api objectApiName;

IMPORTANT -

Lightning Record Pages automatically binds the recordId and objectApiName but if you are using Experience Builder Sites then it does not bind them to the component’s template.

For accessing the record id of the current record you have to add recordId and objectApiName in an expression in the component’s .js-meta.xml file

<targetConfig targets="lightningCommunity__Default">
       <property
       name="recordId" type="String"
       label="Record Id"
       description="This will pass the page record id to the lwc variable"
       default="{!recordId}" />
       <property
       name="objectApiName" type="String"
       label="Object Name"
       description="This will pass the page object name to the lwc variable"
       default="{!objectApiName}" />
    </targetConfig>

If you have any question please leave a comment below.

If you would like to add something to this post please leave a comment below.
Share this blog with your friends if you find it helpful somehow !

Thanks
Let's learn and grow together.
Love and Peace! 

Post a Comment

0 Comments