Sub topic 4
Getting the record context
A record quick action component usually needs to know which record the user is looking at. This chapter covers how the platform passes that information in, when it becomes available, and the mistakes that cause an undefined record ID.
This chapter assumes you can build a basic LWC (template, class, js-meta.xml) and use @api and @wire. It also assumes you know what a record page is and have the lightning__RecordAction target from the previous chapter in place.
What the platform gives you
When a user clicks a record quick action, the platform creates your component and sets two public properties on it:
| Property | Type | Contains | Example |
|---|---|---|---|
| `recordId` | string | The 15- or 18-character ID of the record the action was launched from | `001xx000003DGb2AAG` |
| `objectApiName` | string | The API name of that record's object | `Account`, `Invoice__c` |
You declare both with @api. The platform fills them in. Your component never sets them.
import { LightningElement, api } from 'lwc';
export default class ShowContext extends LightningElement {
@api recordId;
@api objectApiName;
}The property names are fixed. If you call the property accountId or recId, the platform does not populate it. Both screen actions and headless actions receive the same two properties.
Which targets provide context
Only some targets give you a record.
| Target | `recordId` | `objectApiName` |
|---|---|---|
| `lightning__RecordAction` (screen or headless) | Set | Set |
| `lightning__GlobalAction` | Not set | Not set |
A global action is not tied to any record, so both properties stay undefined. If a component is shared between a record action and a global action, check for a missing recordId and handle it.
When the values arrive
The component is created first, and the properties are assigned afterward. This ordering causes most context bugs.
Three practical rules follow from this:
- Do not read
this.recordIdin theconstructor. It is alwaysundefinedthere. - Do not assume
recordIdis set inconnectedCallbackfor a screen action. It usually is, but the timing is not a documented guarantee. Write code that still works if it is not. - In a headless action,
recordIdis set by the time the platform callsinvoke(), so read it there.
The reliable ways to use recordId are to feed it to a wire adapter, read it in an event handler, or react to it in a setter.
Pattern 1: wire adapters with a reactive parameter
Prefix a wire parameter with $ and the framework re-evaluates the wire whenever the property changes. A wire adapter does not run while a required parameter is undefined, so there is no timing problem.
The following component shows the record context and loads the account name. It targets lightning__RecordAction as a screen action, and the js-meta.xml is the same as in the previous chapter.
<template>
<lightning-quick-action-panel header="Record context">
<p>Record ID: {recordId}</p>
<p>Object: {objectApiName}</p>
<template lwc:if={accountName}>
<p>Account name: {accountName}</p>
</template>
<template lwc:elseif={account.error}>
<p>The record could not be loaded.</p>
</template>
</lightning-quick-action-panel>
</template>import { LightningElement, api, wire } from 'lwc';
import { getRecord, getFieldValue } from 'lightning/uiRecordApi';
import NAME_FIELD from '@salesforce/schema/Account.Name';
export default class ShowContext extends LightningElement {
@api recordId;
@api objectApiName;
@wire(getRecord, { recordId: '$recordId', fields: [NAME_FIELD] })
account;
get accountName() {
return this.account && this.account.data
? getFieldValue(this.account.data, NAME_FIELD)
: undefined;
}
}Points to notice:
- The
'$recordId'string is what makes the wire reactive. If you passthis.recordIddirectly, the wire config is evaluated once, at a moment when the value is probablyundefined, and it never updates. NAME_FIELDis imported from@salesforce/schema. The import checks that the field exists at deploy time and respects field-level security. A hard-coded string such as'Account.Name'does neither.- The wire result has
dataanderrorproperties. Neither is set until the first response arrives, so the template must tolerate both being empty.
Pattern 2: a setter on `recordId`
Sometimes you need to run imperative code as soon as the ID arrives, for example to call an Apex method. Put @api on a getter and setter pair and run the code in the setter.
import { LightningElement, api } from 'lwc';
export default class ContextWithSetter extends LightningElement {
_recordId;
loadedFor;
@api
get recordId() {
return this._recordId;
}
set recordId(value) {
this._recordId = value;
if (value) {
this.loadedFor = value;
// Start imperative work here, such as an Apex call keyed on value.
}
}
}The setter runs every time the platform assigns the value, so guard against undefined and make the work safe to repeat. Put @api on only one accessor of the pair (the getter). Decorating both is a compile error.
Pattern 3: read it when the user acts
For many actions, the simplest approach is to read this.recordId inside the handler that does the work. By the time the user clicks Save, the property has long been set.
handleSave() {
const fields = { Id: this.recordId /* plus the fields to change */ };
// call updateRecord({ fields }) as shown in the saving chapter
}The same applies to invoke() in a headless action, where the platform calls the method only after the context is in place.
Using `objectApiName` to make a component generic
The platform tells you which object the action was launched from, so one component can serve several objects. Pass objectApiName where the framework asks for an object. Two common cases:
lightning-record-edit-formandlightning-record-view-formacceptrecord-id={recordId}andobject-api-name={objectApiName}.getRecordaccepts afieldsarray of schema imports. Those imports are static, so a generic component cannot build them fromobjectApiNameat run time. To read fields chosen at run time, usegetRecordwithlayoutTypesandmodes, or usegetObjectInfowith{ objectApiName: '$objectApiName' }to discover fields.
You control which objects can use the component through the action you create in Setup, not through the component. The component only ever sees the object it was launched from.
Common mistakes
- Reading
recordIdin the constructor. It isundefined. Use a reactive wire, a setter, or a handler. - Using
recordIdwithout the$in a wire. The wire is evaluated once withundefinedand never refreshes. - Misspelled property names.
recordID,recordidandobjectNameare not populated, and no error is raised. - Assigning to
recordIdinside the component.@apiproperties are read-only from inside the component. Copy the value into a separate property if you need a modified one. - Expecting context in a global action. A
lightning__GlobalActionhas no record. Ask the user to choose one, for example withlightning-record-picker. - Adding
@tracktorecordId. Public properties are already reactive, so@trackadds nothing.
Checking your understanding
Exercise
A screen action component declares @api recordId; and has @wire(getRecord, { recordId: this.recordId, fields: [NAME_FIELD] }) account;. The record never loads. What is wrong, and how do you fix it?
Show answer
The wire config uses this.recordId directly, so it is evaluated once, before the platform has set recordId, and it does not update afterward. Change the parameter to the reactive string '$recordId': @wire(getRecord, { recordId: '$recordId', fields: [NAME_FIELD] }) account;. The wire then waits for recordId to have a value and re-runs when it changes.
Exercise
You build one component that uses getRecord with @salesforce/schema/Account.Name and add it as a quick action on both Account and Contact. What happens on the Contact page, and what are two ways to avoid it?
Show answer
On Contact, getRecord requests an Account field for a Contact record, so the wire returns an error and no name is shown. You can create the action only on Account and leave it off other layouts, or you can write a component that uses objectApiName (for example with lightning-record-view-form or getObjectInfo) instead of a hard-coded Account field.