Get Record Id in Lightning Component

Get Record Id in Lightning Component

Get Record Id in Lightning Component using  force:hasRecordId

Getting current record id in lightning component or lightning aura component is very easy. We need to add force:hasRecordId interface to a Lightning component to enable the component to be assigned the ID of the current record.

The current record ID is useful if the component is used on a Lightning record page, as an object-specific custom action or action override in Lightning Experience or the Salesforce app, and so on. This interface has no effect except when used within Lightning Experience, the Salesforce mobile app, and template-based communities. If you are looking for how to get current record id in LWC(Lightning Web component), please refer to Get Record Id in Lightning Web Component. If you are looking for how to get current record id in visualforce page please refer to get current record id salesforce

The recordId attribute is set only when you place or invoke the component in an explicit record context. For example, when you place the component directly on a record page layout, or invoke it as an object-specific action from a record page or object home. In all other cases, such as when you invoke the component as a global action, or create the component programmatically inside another component, recordId isn’t set, and your component shouldn’t depend on it.

Sample Code

<aura:component implements="force:lightningQuickAction,force:hasRecordId">
    <!--More lines here-->
</aura:component>

Get Record Id in Lightning Component Example

Lets create a simple lightning component
CurrentrecordIdExample.cmp

<aura:component implements="flexipage:availableForRecordHome,force:hasRecordId" access="global" >
    Account Id is {!v.recordId}
</aura:component>

In this example, we are creating a simple lightning component and displaying record id of record and adding it on account record page.

Now we can add this lightning component on account detail page.

  • Go to Account tab.
  • Open any record.
  • Click Setup (Gear Icon) and select Edit Page.
  • Under Custom Components, find your CurrentrecordIdExample component and drag it on record page.
  • Click Save and activate.

 

We will get the following output

Get Record Id in Lightning Component

We can also use this component as quick action. For that we need to implement force:lightningQuickAction interface instead of flexipage:availableForRecordHome interface.

For more details please refer to official link.

Permanent link to this article: https://www.sfdcpoint.com/salesforce/get-record-id-in-lightning-component/

Leave a Reply

Your email address will not be published.