Sub topic 9
Using recordId and objectApiName on record pages
This chapter assumes you can build a basic Lightning web component (LWC) with an HTML template, a JavaScript class and a .js-meta.xml file. It also assumes you know how to open a Lightning page in App Builder and deploy code with Salesforce CLI. Earlier chapters covered isExposed, targets, @api properties and targetConfigs. Here you will see how a component placed on a record page learns which record it is showing.
What record context is
A record page shows one record, such as a single Account. A component on that page often needs to know which record that is. Salesforce provides this through two public properties that the page fills in for you:
recordIdis the 15- or 18-character ID of the record being displayed. Salesforce supplies the 18-character form.objectApiNameis the API name of that record's object, such asAccount,ContactorInvoice__cfor a custom object.
You do not set these in App Builder. They do not appear in the property panel. The platform assigns them when it creates your component on the page.
The mechanism is a naming convention. If your component declares a public property with exactly one of these names, the record page sets it. The names are case-sensitive, so recordID or objectApiname will never be filled in.
Declaring the properties
Declare both properties with @api:
import { LightningElement, api } from 'lwc';
export default class AccountSummaryCard extends LightningElement {
@api recordId;
@api objectApiName;
@api headerText = 'Summary';
@api maxItems = 5;
}recordId and objectApiName have no default values. The platform sets them. headerText and maxItems are ordinary public properties. An admin can set them in the property panel if you list them in targetConfigs, as the earlier chapters showed.
You only need to declare the properties you use. If your component needs only the record ID, declare only recordId.
Showing the values in a template
The template reads these values like any other property:
<template>
<lightning-card title={headerText} icon-name="standard:account">
<div class="slds-var-p-around_medium">
<p>Record Id: {recordId}</p>
<p>Object: {objectApiName}</p>
<p>Max items: {maxItems}</p>
</div>
</lightning-card>
</template>When you place this component on an Account record page, the card shows the Account's ID and the text Account. On a Contact record page, the same component would show a Contact ID and Contact, provided you allowed that object. The next sections cover how to control that.
Which targets provide record context
Only some page types have a record to give. This table shows what to expect.
| Target | Page | `recordId` | `objectApiName` |
|---|---|---|---|
| `lightning__RecordPage` | Record page | Set | Set |
| `lightning__AppPage` | App page | Not set | Not set |
| `lightning__HomePage` | Home page | Not set | Not set |
On app pages and home pages, both properties stay undefined. This matters when one component supports several targets, as AccountSummaryCard does. The same class runs on all three page types, so your code must handle a missing recordId.
Timing: values are not there in the constructor
The platform sets public properties after it creates the component. That means recordId is undefined inside the constructor(). It is also not guaranteed to be ready at every moment you might expect.
Use these places instead:
connectedCallback()runs after the properties have been set for the first time. It is a safe place to readrecordIdonce.- A setter on the property runs each time the value changes.
- A reactive wire adapter parameter such as
'$recordId'waits until the value is defined.
A getter-and-setter pair is useful when the record can change without the component being recreated. This happens, for example, when a user moves between records in a console app.
import { LightningElement, api } from 'lwc';
export default class RecordWatcher extends LightningElement {
_recordId;
@api
get recordId() {
return this._recordId;
}
set recordId(value) {
this._recordId = value;
if (value) {
this.loadDetails(value);
}
}
loadDetails(id) {
// Replace with real work, such as an Apex call
console.log('Loading details for', id);
}
}The setter checks value before it calls loadDetails. Without the check, your code would run once with undefined on app and home pages.
Using recordId with the wire service
The most common use of recordId is to load data. The @wire decorator with getRecord accepts a reactive parameter. A reactive parameter starts with $ and tells the wire service to re-run when the value changes and to wait while it is undefined.
import { LightningElement, api, wire } from 'lwc';
import { getRecord, getFieldValue } from 'lightning/uiRecordApi';
import NAME_FIELD from '@salesforce/schema/Account.Name';
import INDUSTRY_FIELD from '@salesforce/schema/Account.Industry';
export default class AccountNameCard extends LightningElement {
@api recordId;
@api objectApiName;
@wire(getRecord, { recordId: '$recordId', fields: [NAME_FIELD, INDUSTRY_FIELD] })
account;
get name() {
return getFieldValue(this.account.data, NAME_FIELD);
}
get industry() {
return getFieldValue(this.account.data, INDUSTRY_FIELD);
}
}<template>
<lightning-card title="Account details" icon-name="standard:account">
<div class="slds-var-p-around_medium">
<template lwc:if={account.data}>
<p>Name: {name}</p>
<p>Industry: {industry}</p>
</template>
<template lwc:elseif={account.error}>
<p>Could not load this record.</p>
</template>
</div>
</lightning-card>
</template>This component reads Account fields, so it should only be placed on Account pages. The next section shows how to enforce that.
Limiting a component to specific objects
By default, a component that supports lightning__RecordPage can be placed on a record page for any object. Use the objects element inside a targetConfig to restrict it. This is the same configuration shown in the earlier chapter on targetConfigs:
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>60.0</apiVersion>
<isExposed>true</isExposed>
<masterLabel>Account Summary Card</masterLabel>
<targets>
<target>lightning__AppPage</target>
<target>lightning__HomePage</target>
<target>lightning__RecordPage</target>
</targets>
<targetConfigs>
<targetConfig targets="lightning__AppPage,lightning__HomePage">
<property name="headerText" type="String" label="Header text" default="Summary" />
</targetConfig>
<targetConfig targets="lightning__RecordPage">
<objects>
<object>Account</object>
</objects>
<property name="headerText" type="String" label="Header text" default="Summary" />
<property name="maxItems" type="Integer" label="Maximum items" min="1" max="10" default="5" />
</targetConfig>
</targetConfigs>
</LightningComponentBundle>With this file, the component appears in App Builder only when an admin edits an Account record page. It is hidden on Contact, Opportunity and other object pages. List several <object> elements to allow several objects. Use the object's API name, so a custom object is written as Invoice__c.
The restriction is enforced by App Builder, not by your JavaScript. The objects element controls where an admin can place the component. It does not change what objectApiName contains at run time.
Writing one component for many objects
Sometimes a component should work on several objects. Use objectApiName to build field references at run time instead of hard-coding Account.
You can import a field with @salesforce/schema/Account.Name, but that import is fixed at build time. For a generic component, pass the object's API name to a wire adapter such as getObjectInfo:
import { LightningElement, api, wire } from 'lwc';
import { getObjectInfo } from 'lightning/uiObjectInfoApi';
export default class ObjectLabel extends LightningElement {
@api recordId;
@api objectApiName;
@wire(getObjectInfo, { objectApiName: '$objectApiName' })
objectInfo;
get objectLabel() {
return this.objectInfo.data ? this.objectInfo.data.label : '';
}
}The component shows the label of whichever object the page belongs to. The wire waits until objectApiName is defined, so it makes no call on home and app pages.
<template>
<lightning-card title="Current object">
<p class="slds-var-p-around_medium">This record belongs to: {objectLabel}</p>
</lightning-card>
</template>Common mistakes
- Declaring
recordIdintargetConfigas a property. Do not add<property name="recordId" ...>. The platform fills it in. Adding it can confuse admins by showing a field they cannot meaningfully set, and it is not how record context is passed. - Misspelling the property name.
recordID,recordidandobjectAPINameare different properties. The component deploys without error and the values stayundefined. - Reading
recordIdin the constructor. It is not set yet. UseconnectedCallback, a setter, or a reactive wire parameter. - Assuming a record exists everywhere. On app and home pages
recordIdisundefined. Check it, or use a wire parameter that waits. - Treating
objectsas a runtime guard. It limits placement in App Builder. If a component might also be used inside another component or a Flow screen, handle unexpected object types in code. - Mutating the properties. Public properties are read-only from inside the component. Assigning
this.recordId = 'x'is not allowed. To keep a changeable copy, store it in a private field.
Deploy and test
Deploy the bundle to your default org:
sf project deploy start --source-dir force-app/main/default/lwc/accountSummaryCardThen check the behavior in this order:
- Open Setup, then Object Manager, then Account, then Lightning Record Pages.
- Open an Account record page and choose Edit.
- Find Account Summary Card under Custom components and drag it onto the page.
- Save and activate the page if it is not already active, then open an Account record.
- Confirm the card shows the record's ID and
Account. - Open the home page in App Builder, place the same component, and confirm that
recordIdis blank. This proves the component handles a page with no record.
If the component does not appear on the Account page, check that lightning__RecordPage is listed in targets, that isExposed is true, and that the objects element includes Account.
Exercise
A component declares @api recordId and supports both lightning__RecordPage and lightning__HomePage. It calls loadDetails(this.recordId) inside connectedCallback(). On the home page, the call fails with an error about an undefined ID. What should you change, and why does the problem not occur on a record page?
Show answer
Add a check so the call runs only when recordId has a value, for example if (this.recordId) { this.loadDetails(this.recordId); }. On a record page the platform sets recordId before connectedCallback() runs. On a home page there is no record, so recordId stays undefined. Because the same class runs on both targets, the code must handle both cases.
Exercise
You want a component to appear in App Builder only for Account and Contact record pages, and you want the same component to show the object's label on whichever page it is placed. Name the metadata element you use for the first requirement and the wire adapter you use for the second.
Show answer
Use the <objects> element in the lightning__RecordPage targetConfig, with an <object> entry for Account and one for Contact. For the label, use the getObjectInfo wire adapter from lightning/uiObjectInfoApi, passing '$objectApiName' as a reactive parameter.