How to show Error Message in Lightning Web Component Quick Action in Salesforce?

How to show Error Message in Lightning Web Component Quick Action in Salesforce?

Sample code:

HTML:

<template>
    
</template>

JavaScript:

import { LightningElement, api, wire } from 'lwc';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
import { getRecord } from 'lightning/uiRecordApi';

const FIELDS = [ 'Account.Type' ];

export default class AccountQuickAction extends LightningElement {

    @api recordId;
    type;

    @wire( getRecord, { recordId: '$recordId', fields: FIELDS } )
    wiredRecord({ error, data }) {

        if ( error ) {

            let message = 'Unknown error';
            if (Array.isArray(error.body)) {
                message = error.body.map(e => e.message).join(', ');
            } else if (typeof error.body.message === 'string') {
                message = error.body.message;
            }
            this.dispatchEvent(
                new ShowToastEvent({
                    title: 'Error loading Account',
                    message,
                    variant: 'error',
                }),
            );

        } else if ( data ) {

            console.log( 'Account is ' + JSON.stringify( data ) );
            this.type = data.fields.Type.value;

        }
    }

    @api invoke() {

        console.log( "Inside Invoke Method" );
        console.log( "Record Id is " + this.recordId );

        if ( this.type == 'Prospect' ) {

            this.dispatchEvent(
                new ShowToastEvent({
                    title: 'Account Update Issue',
                    message: 'You cannot update Prospect Account',
                    variant: 'error'
                }),
            );

        }
        

    }

} 

JS-meta.xml:

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>52.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
        <target>lightning__RecordAction</target>
        <target>lightning__RecordPage</target>
    </targets>
    <targetConfigs>
        <targetConfig targets="lightning__RecordAction">
            <actionType>Action</actionType>
        </targetConfig>
    </targetConfigs>
</LightningComponentBundle>

Output:

Leave a Reply