Sub topic 3
Telling the User What Happened with Toasts
Assume you know basic LWC structure, decorators, events, Salesforce record pages, and Salesforce DX deployment. This chapter focuses on feedback, headless actions, setup, refresh behavior, global actions, and testing.
Show Success and Error Toasts
A toast is a short message displayed by Salesforce. Dispatch ShowToastEvent after an operation succeeds or fails.
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
showResult(error) {
this.dispatchEvent(new ShowToastEvent({
title: error ? 'Save failed' : 'Saved',
message: error?.body?.message || 'The record was updated.',
variant: error ? 'error' : 'success'
}));
}For a screen action, show the success toast before dispatching CloseActionScreenEvent. Keep the error toast visible so the user can correct the problem.
Build a Headless Action
A headless action has no visible panel. Salesforce calls its public invoke() method when the user selects the action.
import { LightningElement, api } from 'lwc';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
export default class NotifyRecord extends LightningElement {
@api recordId;
@api invoke() {
this.dispatchEvent(new ShowToastEvent({
title: 'Action ran',
message: `Processed record ${this.recordId}`,
variant: 'success'
}));
}
}Use a headless action for a one-step operation. Use a screen action when the user must enter or review values.
Create and Place the Action
Create the LWC quick action in Setup, then select the component and its action type. Add the resulting action to the object’s page layout under Salesforce Mobile and Lightning Experience Actions. A deployment can create the component, but an administrator still needs to expose the action where users need it.
Refresh Changed Data
After an imperative update, notify Lightning Data Service that the record changed:
import { notifyRecordUpdateAvailable } from 'lightning/uiRecordApi';
await updateRecord({ fields });
await notifyRecordUpdateAvailable([{ recordId: this.recordId }]);This lets components using record data request fresh values.
Global Actions
Use lightning__GlobalAction in js-meta.xml when the action should run outside a specific record page, such as from the global publisher. A global action usually cannot rely on recordId; pass required context through inputs or design the action to operate independently.
Test Common Pitfalls with Jest
Test the component’s behavior rather than Salesforce’s base components. Mock ShowToastEvent, updateRecord, and notifyRecordUpdateAvailable. Common failures include forgetting @api invoke(), assuming recordId exists in a global action, and asserting a toast before pending promises settle.
Exercise
Which action type should you choose for a form that edits a record description?
Show answer
Choose a screen action, because the user must enter or review a value before saving.