Display Toast Notifications in Lightning Web Components (LWC) : Abhijeet

Display Toast Notifications in Lightning Web Components (LWC)
by: Abhijeet
blow post content copied from  SalesForce FAQs
click here to view original post



### Summary of Toast Notifications in Salesforce LWC In Salesforce Lightning Web Components (LWC), toast notifications are temporary pop-up messages that inform users about the success, failure, or status of an action. This tutorial covers how to implement toast notifications using the `lightning/platformShowToastEvent` module. #### Key Points: 1. **Types of Toast Notifications**: - **Success**: Indicates a successful operation. - **Error**: Alerts the user about an issue. - **Warning**: Warns the user about potential problems. - **Info**: Provides additional information. 2. **Toast Message Modes**: - **Dismissable**: Can be closed manually and auto-closes after 5 seconds. - **Pester**: Cannot be closed manually and auto-dismisses after 3 seconds. - **Sticky**: Remains on the screen until manually closed. 3. **Implementation Steps**: - Import `ShowToastEvent` from the module. - Create a JavaScript file to define toast messages. - Create an HTML file to render buttons that trigger the toast notifications. - Use a meta.xml file to expose the component to Lightning pages. 4. **Reusable Toast Notification Utility**: - Create a utility component to streamline the toast notification process, allowing for easy reuse across different components. 5. **Use Case Example**: - A component that creates account records and displays appropriate toast messages based on user input, such as success, warning, error, and info notifications. ### Additional Context: Toast notifications enhance user experience by providing immediate feedback on actions taken within the application. They are particularly useful for confirming successful operations or alerting users to issues without requiring them to navigate away from their current task. ### Conclusion: This tutorial provides a comprehensive guide to implementing toast notifications in Salesforce LWC, including creating reusable components and practical use cases for displaying notifications based on user interactions. ### Relevant Hashtags for SEO: #Salesforce #LWC #ToastNotifications #LightningWebComponents #SalesforceDevelopment #WebDevelopment #UserExperience #SalesforceTutorial #JavaScript #Apex #SalesforceAdmin


In Salesforce LWC components, we use toast message to display temporary pop-up notifications on the screen to inform users about an action’s success, failure, or status.

In this Salesforce tutorial, we will learn about Toast notification feature in LWC and how to display toast notification in Salesforce Lightning web components.

What Are Toast Notifications in LWC?

In Salesforce, Toast notifications are provided by the lightning/platformShowToastEvent module. The toast message is displayed on screen after a trigger such as saving records or getting an error. Using the toast notification feature, we can display success, error, info, and warning messages in a pop-up message.

In the LWC toast notification feature, we get four types of toast messages that we display in a pop-up message on the screen.

  • Success: Indicates that an operation was successful.
  • Error: Alerts the user about an issue.
  • Warning: Warns the user about a problem or confirmation.
  • Info: Provides additional information to the user. 

Button modes for displaying toast notification:

The messages are displayed on the screen in three modes, which are dismissable, pester, and sticky. The mode of the message is defined by the mode attribute, such as mode: ‘dismissable’. If the mode is not defined, the message will take dismissable as the default mode.

The function of all three toast message modes is as follows:

  • Dismissable – With this mode the toast message appears with a close button and remains visible for 5 seconds by default. We can manually close it by clicking the close button before the timer expires. If not closed manually, it auto-closes after 5 seconds.
  • Pester – The pester mode toast appears without a close button and auto-dismisses after 3 seconds. It cannot be closed manually, and is generally used to show info messages or notifications that don’t require interaction.
  • Sticky – When using this mode, the message will be on the screen until we close it, generally used to display error messages.

Displaying Toast Messages in Salesforce LWC Components

To display a toast message in the LWC component, we need to import ShowToastEvent from the lightning/platformShowToastEvent module.

To implement the toast messages in the LWC components, create a LWC component and follow the steps below.

In the below example, we will create an LWC component that displays all toast messages, including success, error, info, and warning.

1. Create an LWC component and enter the code below in the JS file.

import { LightningElement } from 'lwc';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';

export default class ToastNotifications extends LightningElement {
  
    showSuccessToast() {
        const event = new ShowToastEvent({
            title: 'Success!',
            message: 'Your record has been saved successfully.',
            variant: 'success',
            mode: 'dismissable' 
        });
        this.dispatchEvent(event);
    }

    showErrorToast() {
        const event = new ShowToastEvent({
            title: 'Error!',
            message: 'Error occured, Please try again.',
            variant: 'error',
            mode: 'sticky' 
        });
        this.dispatchEvent(event);
    }

    showWarningToast() {
        const event = new ShowToastEvent({
            title: 'Warning!',
            message: 'Data is incomplete.',
            variant: 'warning',
            mode: 'pester' 
        });
        this.dispatchEvent(event);
    }

    showInfoToast() {
        const event = new ShowToastEvent({
            title: 'Info',
            message: 'This is a notification for your information.',
            variant: 'info',
            mode: 'dismissable'
        });
        this.dispatchEvent(event);
    }
}

In this, we first imported the toast notification feature from the Lightning by using the method import{ ShowToastEvent } from ‘lightning/platformShowToastEvent’. After this, we created events to define the toast messages that will trigger on button click.

For the toast messages, we defined the attributes title for the message title, message for the custom message text, variant to define the toast notification icon (warning, success, error, and info) and notification mode.

2. After defining the toast notification logic, enter the code below in the html file to render the UI of buttons through which we will trigger and display toast notifications.

<template>
    <lightning-card title="Toast Notifications">
        <div class="slds-p-around_medium">
            <lightning-button label="Show Success Toast" variant="brand" onclick={showSuccessToast}></lightning-button>
            <lightning-button label="Show Error Toast" variant="destructive" onclick={showErrorToast}></lightning-button>
            <lightning-button label="Show Warning Toast" variant="neutral" onclick={showWarningToast}></lightning-button>
            <lightning-button label="Show Info Toast" variant="base" onclick={showInfoToast}></lightning-button>
        </div>
    </lightning-card>
</template>

In this HTML file, we have defined the buttons UI through which we will call the events to display the toast notifications using onclick={showSuccessToast} and other onclick events.

We have also defined variants for the buttons, such as brand for success button, destructive for red error button, neutral for warning with white button, and base variant to display the info toast message.

3. Enter the code below in the meta.xml file inside the Lightning component bundle tag to make the LWC component available for the Lightning pages.

<isExposed>true</isExposed>
    <targets>
        <target>lightning__RecordPage</target>
        <target>lightning__AppPage</target>
        <target>lightning__HomePage</target>
    </targets>

4. Deploy the LWC component to the lightning page, and there you will see buttons in the UI of the LWC component.

Salesforce LWC Toast Notifications

As we click on the button, it will call the assigned event and display toast notifications accordingly.

Display Toast Notifications in LWC Components

This way, we can display toast notifications in the LWC component using the platformShowToastEvent and defining events to call them through a trigger or a button.

Create Reusable Toast Notification Utility

In Salesforce, displaying toast notifications is required for many use cases, so instead of defining all the attributes of the toast events repeatedly for each time you want to display a toast notification, we can create a reusable toast notification utility component.

With this, we can export the toast feature in another LWC component to define the toast notifications.

Follow the below steps to create a reusable utility component for toast notifications.

1. Create a new LWC component and enter the code below in the JS file. Since it is a utility component, we don’t need to define UI in HTML and expose it to lightning pages via meta.xml code.

import { ShowToastEvent } from 'lightning/platformShowToastEvent';

export function showToast(component, title, message, variant, mode = 'dismissable') {
    const event = new ShowToastEvent({
        title,
        message,
        variant,
        mode
    });
    component.dispatchEvent(event);
}

In this component, we have imported the ShowToastEvent from Lightning and defined all attributes title, message, variant, and mode in a function. We have also defined the default notification of toast messages using mode = ‘dismissable’.

2. To use this toast notification utility component, we have to import it into the LWC component, which is where we use the toast notification feature.

To import this utility component, we can define the JS code of the LWC component as below.

import { LightningElement } from 'lwc';
import { showToast } from 'c/toastUtility';

export default class ToastDemo extends LightningElement {
    showSuccessToast() {
        showToast(this, 'Success!', 'Your record has been saved successfully.', 'success');
    }

    showErrorToast() {
        showToast(this, 'Error!', 'Something went wrong. Please try again.', 'error', 'sticky');
    }

    showWarningToast() {
        showToast(this, 'Warning!', 'Proceed with caution.', 'warning', 'pester');
    }

    showInfoToast() {
        showToast(this, 'Info', 'This is a neutral notification.', 'info');
    }
}

In this component, we first import the utility component using import { showToast } from ‘c/toastUtility’.

In this, we don’t need to define the attributes of the toast notifications, such as title, message, variant, and mode. We just need to assign the values of the attributes in an order. For example, to display a success toast, we will define it as below.

showSuccessToast() {
        showToast(this, 'Success!', 'Your record has been saved successfully.', 'success');
    }

In this, we have defined the values of title, message, and variant. If we don’t include the mode value, it will take the default dismissable mode.

This way, we can create a reusable utility component for the lighting toast notifications.

Use Case Scenario to Display Toast Notifications in LWC Component

In the below example, we will see a real-time use case of displaying a toast message on the lightning web components.

Through this LWC component, we will create account records with field input of Account name, with the following toast messages.

  • Success – When entering a valid account name and saving the record.
  • Warning – If the account name includes “test” in the name.
  • Error – When the account name contains numbers or it is blank.
  • Info – When the account is saved, the info toast message will show the created account’s id.

Follow the steps below to create a LWC component that will display toast messages according to the above conditions.

1. First, we need to create a controller class that will save the account records in the database and handle exceptions for blank input, which will show an error.

public with sharing class AccountController {
    @AuraEnabled
    public static String createAccount(String accountName) {
        try {
            if (String.isBlank(accountName)) {
                throw new AuraHandledException('Account name cannot be blank.');
            }
            
            Account acc = new Account(Name = accountName);
            
            return acc.Id;
        } catch (Exception e) {
            throw new AuraHandledException(e.getMessage());
        }
    }
}

2. Create an LWC component accountCreator and enter the code below in the JS file to define the logic of displaying toast notifications and saving the account record.

import { LightningElement, track } from 'lwc';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
import createAccount from '@salesforce/apex/AccountController.createAccount';

export default class AccountCreator extends LightningElement {
    @track accountName = '';

    handleNameChange(event) {
        this.accountName = event.target.value;
    }

    async handleSave() {
        try {
            if (this.accountName.toLowerCase().includes('test')) {
                this.showWarningToast();
                return;
            }
            if (/\d/.test(this.accountName)) {
                this.showErrorToast('Account name cannot contain numbers.');
                return;
            }

            const accountId = await createAccount({ accountName: this.accountName });
            this.showSuccessToast(accountId);
            this.showInfoToast(accountId);

        } catch (error) {
            this.showErrorToast(error.body.message);
        }
    }

    showSuccessToast(accountId) {
        this.dispatchEvent(
            new ShowToastEvent({
                title: 'Success!',
                message: 'Account created with ID: ${accountId}',
                variant: 'success',
                mode: 'dismissable'
            })
        );
    }

    showErrorToast(errorMessage) {
        this.dispatchEvent(
            new ShowToastEvent({
                title: 'Error!',
                message: errorMessage || 'Failed to create account.',
                variant: 'error',
                mode: 'sticky'
            })
        );
    }

    showWarningToast() {
        this.dispatchEvent(
            new ShowToastEvent({
                title: 'Warning!',
                message: 'Account name contains "Test" - Enter valid name',
                variant: 'warning',
                mode: 'pester'
            })
        );
    }

    showInfoToast(accountId) {
        this.dispatchEvent(
            new ShowToastEvent({
                title: 'Info',
                message: 'Account Number will be generated soon for ID: ${accountId}',
                variant: 'info',
                mode: 'dismissable'
            })
        );
    }
}

In this code, we have defined the logic for saving the record. When the user clicks on save after entering input, the handleNameChange event triggers, checking the input and returning the toast messages according to that.

3. Enter the code below in the HTML file to render the UI of LWC component and toast messages.

<template>
    <lightning-card title="Create Account" >
        <div class="slds-p-around_medium">
            <lightning-input 
                label="Account Name" 
                value={accountName} 
                onchange={handleNameChange} 
                placeholder="Enter account name">
            </lightning-input>
            <div class="slds-m-top_small">
                <lightning-button 
                    label="Save Account" 
                    variant="brand" 
                    onclick={handleSave}>
                </lightning-button>
            </div>
        </div>
    </lightning-card>
</template>

The onchange attribute calls the event that checks the input for the entered name, and the handleSave event saves the records. If a valid input is given, it will return success and info; otherwise, it will return an error and warning toast notification.

3. Expose the LWC component to the lighting page by entering the code below in the meta.xml file inside the <LightningComponentBundle> tag.

<targets>
        <target>lightning__AppPage</target>
        <target>lightning__RecordPage</target>
        <target>lightning__HomePage</target>
 </targets>

4. Deploy the LWC component to the Lightning page, using the Lightning App builder.

5. When the user gives input to create an account and clicks Save, it will trigger the event to display the toast messages according to the above mentioned conditions.

For Success and Info toast message:

How to display Toast Notification in LWC component

For Warning toast message:

Display warning toast message in LWC component

For Error Toast message:

Display Error Toast Notification in LWC component

The toast message is displayed on the screen according to the provided input values. This way, we can apply conditional logic to trigger and display the lightning toast notification in lightning web components.

Conclusion

In this Salesforce tutorial, we have learned about the Lightning toast notification feature, and we created a LWC component in which we learned how to set up the Lightning toast notification by defining the attributes of the toast message and triggering them using events.

After this, we also created a reusable utility component to call the toast message from this component to other components whenever required. At last, we used a real-time example, creating accounts using LWC and displaying toast messages according to the defined conditions.

You may also like to read:

The post Display Toast Notifications in Lightning Web Components (LWC) appeared first on SalesForce FAQs.


March 07, 2025 at 07:29PM
Click here for more details...

=============================
The original post is available in SalesForce FAQs by Abhijeet
this post has been published as it is through automation. Automation script brings all the top bloggers post under a single umbrella.
The purpose of this blog, Follow the top Salesforce bloggers and collect all blogs in a single place through automation.
============================

Salesforce