Sub topic 5
Building a Screen Action
A screen action is a Lightning web component (LWC) that opens in a modal panel when a user clicks a quick action button on a record page. This chapter builds one end to end: an "Update Description" action on Account. The user edits the description, clicks Save, sees a toast, and the panel closes.
Prerequisites
This chapter assumes you can already do the following:
- Write an LWC with an HTML template, a JavaScript class, and a
js-meta.xmlfile. - Use
@apiproperties and dispatch and handle events. - Deploy components with a Salesforce DX project.
- Read a record page and page layout in Lightning App Builder or Setup.
Earlier chapters covered the screen versus headless choice, the lightning__RecordAction target, and recordId. Here they are used, not re-explained.
What You Are Building
A screen action has three parts, and the platform connects them:
- Metadata declares the component as a record action of type
ScreenAction. - Template renders the panel header, body, and footer buttons.
- JavaScript class receives
recordId, saves the record, shows feedback, and asks the platform to close the panel.
The platform creates the component when the user clicks the action. It sets recordId and hosts the component inside its own modal. Your component never opens or removes that modal itself. It only dispatches a close event.
Step 1: Expose the Component
The js-meta.xml file makes the component available as a record quick action and sets its type to ScreenAction.
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>60.0</apiVersion>
<isExposed>true</isExposed>
<targets>
<target>lightning__RecordAction</target>
</targets>
<targetConfigs>
<targetConfig targets="lightning__RecordAction">
<actionType>ScreenAction</actionType>
</targetConfig>
</targetConfigs>
</LightningComponentBundle>Two details matter:
isExposedmust betrue. If it isfalse, the component never appears in the Setup list of components for a quick action.actionTypedecides how the platform treats the component. WithScreenAction, the platform shows a modal and the component supplies the content. WithAction, the platform instead calls a publicinvoke()method and shows no UI. PickScreenActionwhenever the user must see or enter something.
Step 2: Lay Out the Panel
The template uses lightning-quick-action-panel. It supplies the modal header and body. The footer slot holds the buttons.
<template>
<lightning-quick-action-panel header="Update Description">
<lightning-textarea
label="Description"
value={description}
onchange={handleChange}>
</lightning-textarea>
<div slot="footer">
<lightning-button variant="neutral" label="Cancel" onclick={handleCancel}></lightning-button>
<lightning-button variant="brand" label="Save" onclick={handleSave} disabled={isSaving}></lightning-button>
</div>
</lightning-quick-action-panel>
</template>Notice the following:
- The
headerattribute sets the modal title. You do not build a close "X" button, because the platform adds it. - Anything outside the
footerslot goes in the body. - The Save button has
disabled={isSaving}. That attribute stops a second click from sending a duplicate save while the first is in flight. - Cancel is your responsibility. The "X" closes the modal, but a Cancel button in the footer is a normal pattern, and you have to wire it yourself.
Step 3: Write the Class
import { LightningElement, api } from 'lwc';
import { CloseActionScreenEvent } from 'lightning/actions';
import { updateRecord } from 'lightning/uiRecordApi';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
import ID_FIELD from '@salesforce/schema/Account.Id';
import DESCRIPTION_FIELD from '@salesforce/schema/Account.Description';
export default class UpdateDescription extends LightningElement {
@api recordId;
description = '';
isSaving = false;
handleChange(event) {
this.description = event.target.value;
}
handleCancel() {
this.dispatchEvent(new CloseActionScreenEvent());
}
async handleSave() {
this.isSaving = true;
const fields = {};
fields[ID_FIELD.fieldApiName] = this.recordId;
fields[DESCRIPTION_FIELD.fieldApiName] = this.description;
try {
await updateRecord({ fields });
this.dispatchEvent(new ShowToastEvent({
title: 'Success',
message: 'Description updated',
variant: 'success'
}));
this.dispatchEvent(new CloseActionScreenEvent());
} catch (error) {
this.dispatchEvent(new ShowToastEvent({
title: 'Error updating record',
message: error?.body?.message || 'Unknown error',
variant: 'error'
}));
} finally {
this.isSaving = false;
}
}
}How the Save Flow Works
updateRecord takes a record input with a fields object. For an update, fields must contain the record Id plus every field you want to change. Fields you leave out stay as they are.
The code builds the keys from fieldApiName on the imported schema references. Importing @salesforce/schema/Account.Description has two benefits over a hard-coded string:
- A typo fails at deploy time, not at run time.
- Salesforce tracks the dependency, so a field cannot be deleted while the component uses it.
The try, catch, and finally blocks split the outcomes:
| Outcome | What the user sees | Panel |
|---|---|---|
| `updateRecord` resolves | Success toast | Closed |
| `updateRecord` rejects | Error toast with the server message | Stays open, so the user can fix the input and retry |
| Cancel clicked | Nothing | Closed |
The panel stays open on failure. That matters because the user keeps what they typed. If you closed the panel in finally, an error would throw away their edit.
The error shape is the one the Lightning Data Service (LDS) returns. The readable text is usually at error.body.message. Validation rule failures and field-level problems can instead appear in error.body.output. The ?. operator keeps the handler from throwing when body is missing, such as on a network failure.
Step 4: Add the Action in Setup
After you deploy the bundle, create the action:
- In Setup, go to Object Manager, open Account, then Buttons, Links, and Actions.
- Click New Action.
- Set Action Type to Lightning Web Component and choose
c:updateDescriptionfrom the component list. - Enter a label such as "Update Description" and save.
- Open the page layout, find the Salesforce Mobile and Lightning Experience Actions section, and drag the new action in.
Layout placement is covered in a later chapter. For now, it is enough to know that an action that is not on the layout is not visible to users, however correct the code.
Edge Cases and Common Errors
The Description Field Starts Empty
The textarea starts empty because description is ''. If the account already has a description, clicking Save without typing replaces it with an empty string. Fix this in one of two ways:
- Load the current value with
getRecordandgetFieldValuefromlightning/uiRecordApi, then seeddescriptionfrom the result. - Skip the save when the user has not changed anything.
For a real action, one of these is almost always required.
`recordId` Is Not Available Early
The platform sets recordId after it creates the component. You can read it in handleSave because the user cannot click until the panel renders. Reading this.recordId in the constructor returns undefined. If you need it at load time, use connectedCallback, or use a setter on the @api property.
The Component Works on One Object Only
This component imports Account.Description, so it only makes sense on Account. If you add it to Contact, the update sends an Account field for a Contact ID and fails. For a reusable action, read objectApiName, which the platform also supplies, and build the field list from it.
The Panel Component Only Works in an Action
lightning-quick-action-panel is meant to be hosted by the quick action modal. If you place the same component on a record page in App Builder, the markup will not behave like a modal. Keep action components separate from page components.
Closing Does Not Refresh the Page
updateRecord updates the LDS cache. Record forms and getRecord wires on the page refresh automatically. Data that your own Apex calls load does not. Refreshing that data is covered in a later chapter.
Duplicate Saves
Setting isSaving before the await and clearing it in finally is what protects against a double click. Without it, two fast clicks send two updates.
Summary of the Pattern
Every screen action follows the same shape:
- Metadata sets
lightning__RecordActionandScreenAction. - The template wraps content in
lightning-quick-action-panel, with buttons in thefooterslot. - The class declares
@api recordId, does its work in an async handler, reports with a toast, and dispatchesCloseActionScreenEvent.
Exercise
In the Update Description action, a user types a description, clicks Save, and the save fails because of a validation rule. What happens to the panel and the typed text, and why? Which line of the class would you change to make the panel close on failure, and why would that be a poor choice?
Show answer
The error toast appears and the panel stays open. The typed text is kept because the catch block only shows a toast and does not dispatch CloseActionScreenEvent, and description still holds the value. finally only sets isSaving back to false, so the Save button is enabled again for a retry. To close the panel on failure you would dispatch new CloseActionScreenEvent() inside the catch block (or move it into finally). That is a poor choice because the user would lose their edit and would have to reopen the action and retype it after reading the error.