Sub topic 13
Global actions
What a global action is
A global action is a quick action that is not tied to a record. It appears in the global actions menu (the + icon in the Lightning Experience header) and in other places that show global actions, such as the Home page. You use one when the work makes sense anywhere in the org: logging a call, creating a task, or starting a new lead from a short form.
This chapter assumes you have read the earlier chapters on js-meta.xml targets, screen actions, CloseActionScreenEvent, and toasts. Most of that carries over. The main difference is that a global action has no record context.
How global actions differ from record actions
A record action runs against one record, and the platform passes that record's Id to the component. A global action runs with nothing to pass, so the component starts with no record to work on.
| Aspect | Record action | Global action |
|---|---|---|
| Target in `js-meta.xml` | `lightning__RecordAction` | `lightning__GlobalAction` |
| `recordId` | Set by the platform | Not set (`undefined`) |
| `objectApiName` | Set by the platform | Not set (`undefined`) |
| Created in Setup | On a specific object | Under Global Actions |
| Added to | An object's page layout | The Global Publisher Layout |
| Typical job | Change or act on this record | Create something or run a utility |
Because there is no record, a global action usually does one of three things:
- It creates a new record with
createRecord. - It asks the user to choose a record, for example with
lightning-record-picker, and then works on that choice. - It calls Apex or an external service that does not need a record.
Exposing the component
For a global action, the js-meta.xml file lists the lightning__GlobalAction target. The minimal file looks like this:
<?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__GlobalAction</target>
</targets>
</LightningComponentBundle>This file has no targetConfig block, so the component runs as a screen action that opens a panel. Check the current Salesforce documentation before you rely on a headless (Action) global action. Support for the headless type and for actionType on this target has changed between releases.
The same component can be exposed to more than one target. List both targets if you want one component to work as a record action and as a global action:
<targets>
<target>lightning__RecordAction</target>
<target>lightning__GlobalAction</target>
</targets>
<targetConfigs>
<targetConfig targets="lightning__RecordAction">
<actionType>ScreenAction</actionType>
</targetConfig>
</targetConfigs>If you do this, the JavaScript must handle both cases. recordId is set on a record page and undefined in the global menu.
A worked example: a quick task
This global action creates a Task that is not linked to any record. The Subject field is required on Task, so the form validates it before saving.
The template uses the same panel as a record action:
<template>
<lightning-quick-action-panel header="Quick Task">
<lightning-input
label="Subject"
value={subject}
required
onchange={handleSubjectChange}>
</lightning-input>
<lightning-textarea
label="Notes"
value={notes}
onchange={handleNotesChange}>
</lightning-textarea>
<div slot="footer">
<lightning-button variant="neutral" label="Cancel" onclick={handleCancel}></lightning-button>
<lightning-button variant="brand" label="Create" onclick={handleCreate} disabled={isSaving}></lightning-button>
</div>
</lightning-quick-action-panel>
</template>The JavaScript class has no @api recordId, because the platform does not supply one:
import { LightningElement } from 'lwc';
import { CloseActionScreenEvent } from 'lightning/actions';
import { createRecord } from 'lightning/uiRecordApi';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
import TASK_OBJECT from '@salesforce/schema/Task';
import SUBJECT_FIELD from '@salesforce/schema/Task.Subject';
import DESCRIPTION_FIELD from '@salesforce/schema/Task.Description';
export default class QuickTask extends LightningElement {
subject = '';
notes = '';
isSaving = false;
handleSubjectChange(event) {
this.subject = event.target.value;
}
handleNotesChange(event) {
this.notes = event.target.value;
}
handleCancel() {
this.dispatchEvent(new CloseActionScreenEvent());
}
async handleCreate() {
const subjectInput = this.template.querySelector('lightning-input');
if (!subjectInput.reportValidity()) {
return;
}
this.isSaving = true;
const fields = {};
fields[SUBJECT_FIELD.fieldApiName] = this.subject;
fields[DESCRIPTION_FIELD.fieldApiName] = this.notes;
try {
await createRecord({ apiName: TASK_OBJECT.objectApiName, fields });
this.dispatchEvent(new ShowToastEvent({
title: 'Success',
message: 'Task created',
variant: 'success'
}));
this.dispatchEvent(new CloseActionScreenEvent());
} catch (error) {
this.dispatchEvent(new ShowToastEvent({
title: 'Error creating task',
message: error?.body?.message || 'Unknown error',
variant: 'error'
}));
} finally {
this.isSaving = false;
}
}
}Compare this with the record action from the earlier chapters:
createRecordreplacesupdateRecord, because no existing record is being changed.- The
fieldsobject has noId. ForcreateRecord, you passapiNameandfields. The Id comes back in the result. - The Task's
OwnerIddefaults to the running user, so the form does not set it. - The panel, toast, and close logic are identical.
Letting the user pick a record
Sometimes a global action needs an existing record. The component cannot read one from the page, so the user has to choose it. lightning-record-picker is one option:
<lightning-record-picker
label="Account"
object-api-name="Account"
onchange={handleAccountChange}>
</lightning-record-picker>handleAccountChange(event) {
this.selectedAccountId = event.detail.recordId;
}From there, use selectedAccountId the way a record action uses recordId. For example, pass it as WhatId when you create the Task. Treat it as nullable, because the user can clear the picker.
Creating the action and adding it to a layout
Creating a global action in Setup has the same shape as creating a record action, with a different starting point:
- Deploy the component to the org. Quick actions can only list components that are already deployed and exposed.
- In Setup, open Global Actions (search for it in Quick Find) and click New Action.
- Set Action Type to Lightning Web Component, then choose your component in Lightning Web Component.
- Enter a Label and save. The label is what users see in the menu. Setup generates the Name from it, and you cannot change the name later.
- Open Publisher Layouts in Setup, edit the Global Publisher Layout, and drag the new action into the Quick Actions in the Salesforce Classic Publisher section (or the Lightning Experience actions section, depending on your org's layout editor). Save.
Users then see the action under the + icon. Where else it shows up depends on the page. Check the Home page and any app pages that use the global actions region.
Global actions can also be added to an object's page layout, in the same quick actions section used for record actions. They still run without a record Id even there. Do not read recordId on the assumption that the layout supplies it.
Edge cases and pitfalls
- Assuming
recordIdexists. If you reuse a component on both targets, guard every use:if (this.recordId) { ... }. A call toupdateRecordwithId: undefinedfails with a confusing validation error. - Forgetting to add the action to the layout. Creating the action does not make it visible. It must be placed in the Global Publisher Layout.
- Changing the component name after creating the action. The action keeps a reference to the component. Renaming or deleting a component that is referenced by an action blocks the deployment or breaks the action.
- Expecting a view refresh. A global action has no record page to refresh. If the user is on a record page when they run the action, and you changed that page's record, call
notifyRecordUpdateAvailablewith that record's Id, as covered in the refresh chapter. Otherwise the page shows stale data. - Blank states after Cancel. The panel component is created fresh each time the action opens, so field values reset. Do not rely on state from a previous run.
- Missing permissions. The user needs create access to the object and field-level access to the fields you set.
createRecordfails with anerror.body.messagethat names the cause. Show it in the error toast.
Testing
A global action is easier to test than a record action, because there is no recordId to inject. In Jest, create the element, set the inputs, click the button, and check the calls to createRecord. Mock createRecord and the CloseActionScreenEvent listener. The pitfalls above show what to test: an empty Subject must not call createRecord, a failed save must show an error toast and leave the panel open, and a successful save must dispatch the close event.
Exercise
You wrote a component exposed to both lightning_RecordAction and lightning_GlobalAction. It updates the Description of an Account with updateRecord using this.recordId. Users report an error when they run it from the global menu. Why does it fail, and what are two ways to fix it?
Show answer
In the global menu the platform does not set recordId, so this.recordId is undefined and updateRecord is called with no record Id. One fix is to guard the save: check this.recordId and show an error toast, or hide the save button, when it is missing. Another fix is to let the user choose the Account (for example with lightning-record-picker) and use the selected Id. A third option is to expose the component only to lightning__RecordAction.
Exercise
Name two steps, beyond deploying the component, that you must complete in Setup before users can see a new global LWC action.
Show answer
Create the action under Global Actions with Action Type set to Lightning Web Component and the component selected, then add the action to the Global Publisher Layout in Publisher Layouts.