Sub topic 3
Using Record Context on Lightning Record Pages
Assume you know the basic HTML, JavaScript, and metadata files in a Lightning web component (LWC), plus basic XML syntax and Salesforce CLI deployment.
Using `recordId` and `objectApiName`
A component placed on a Lightning record page can receive context about the current record. Declare recordId and objectApiName as public properties with @api. Salesforce supplies their values when the component runs on a record page.
import { LightningElement, api } from 'lwc';
export default class AccountSummaryCard extends LightningElement {
@api recordId;
@api objectApiName;
@api headerText = 'Summary';
}The template can display or use these values:
<template>
<lightning-card title={headerText}>
<div class="slds-var-p-around_medium">
<p>Record Id: {recordId}</p>
<p>Object: {objectApiName}</p>
</div>
</lightning-card>
</template>The values are available only when Salesforce supplies record context. A component on a home page does not automatically receive a record ID.
Limiting the Component to Specific Objects
Use the objects element inside the lightning__RecordPage target configuration to limit placement to selected objects.
<targetConfig targets="lightning__RecordPage">
<objects>
<object>Account</object>
</objects>
<property name="headerText" type="String"
label="Header text" default="Summary" />
</targetConfig>This component appears for Account record pages, but not for Contact or Opportunity record pages. The object name must match a Salesforce API object name.
Supporting Desktop and Phone
Use supportedFormFactors when the component should be available on particular device types.
<supportedFormFactors>
<supportedFormFactor type="Large" />
<supportedFormFactor type="Small" />
</supportedFormFactors>Large represents desktop-sized displays. Small represents phone-sized displays. Include only form factors that your layout supports.
Deploying and Adding the Component
Deploy the LWC bundle:
sf project deploy start --source-dir force-app/main/default/lwc/accountSummaryCardIn Lightning App Builder, open an existing record page or create one. Find the component under Custom Components, drag it onto the canvas, set its properties, and save and activate the page.
Troubleshooting Missing Components or Properties
- Confirm that the metadata file ends in
.js-meta.xml. - Set
<isExposed>true</isExposed>. - Add the correct page target, such as
lightning__RecordPage. - Ensure each configurable property has a matching
@apiproperty. - Check that the property is inside the applicable
targetConfig. - Redeploy the complete component bundle.
- Verify that the selected record object matches the
<objects>restriction. - Refresh App Builder after deployment.
Exercise
Why might recordId be empty when the same component is placed on a Home page?
Show answer
Home pages do not provide automatic record context, so Salesforce does not supply recordId there.