Display Notifications in Salesforce Lightning Web Components

In Salesforce Lightning Web Components, we can display custom notifications using the built-in alert, prompt, and confirm modals.

There are several scenarios in which we need to display notifications in Lightning Web Components. For example, displaying a success alert upon record creation, a confirmation alert when deleting, or a prompt alert when updating records in Salesforce.

Apart from the alert, confirm, and prompt modals, we also have the Toast Notifications feature in Salesforce. This feature is ideal for providing users with short, immediate feedback through notifications.

In this Salesforce tutorial, we will learn how to display notifications in Salesforce Lightning Web Components.

Notifications in Salesforce Lightning Web Components

In Salesforce Lightning, we have several inbuilt modules that enable us to display notifications to users.

  • LightningAlert
  • LightningPrompt
  • LightinngConfirm

In the examples below, we will discuss the use cases of these lightning notification modules.

Use Lightning Alert in Salesforce Lightning Web Components

The Lightning alert module is used to display alerts on pop-up screens that require the user’s attention, such as warnings or success messages.

In the lightning alert module, we have three variants:

  • Success – to display a success message in a green theme.
  • Error – to show the error message in the red theme.
  • Warning – shows an alert warning message in the yellow theme.

The variant can be changed by setting the theme attribute as mentioned below. The alert component can be set in three different properties.

  • Message – the message that wants to be displayed on the dialog.
  • Theme – this is used to change the variant of the component.
  • Label – This is the header label for the dialog.

Let’s create a lightning web component that displays all three alert notifications (alert, error, warning) upon button click.

Navigate to the VS Code IDE and to create a Lightning Web Component, press Ctrl+Shift+P keys to open the command palette, and there select SFDX: Create a Lightning Web Component.

Display alert notification in Salesforce LWC

Give a name for the lightning web component in camel case, such as alertModal, and press Enter. After this, you will get files alertModal.js, alertModal.html, and alertModalmeta.html.

Enter the below code in the JS file to define the properties of the alert message, which are message, theme, and label.

To get the Lightning alert notification, we have used the import method import LightningAlert from “lightning/alert”.

import { LightningElement } from 'lwc';
import LightningAlert from "lightning/alert";
 
export default class AlertModal extends LightningElement {
  async showAlertSuccess() {
    await LightningAlert.open({
      message: "This is the Success alert message.",
      theme: "success",
      label: "Success!",
    });
  }

  async showAlertError() {
    await LightningAlert.open({
      message: "This is the Error alert message.",
      theme: "error",
      label: "Error!",
    });
  }

  async showAlertWarning() {
    await LightningAlert.open({
      message: "This is the warning alert message.",
      theme: "warning",
      label: "Warning!",
    });
  }
}

In the above code, we have defined success, error, and warning alert notifications. The LightningAlert.open() method is used to display the alert, where you can customize the message, theme, and label (which appears as the alert title).

We will display these alert notifications on the screen using the button click, so for that, we need to define the UI of the LWC using the code below in the HTML file.

<template>
    <lightning-button label="Show Success Alert" title="Show Alert" onclick={showAlertSuccess}>
    </lightning-button>
    <lightning-button label="Show Error Alert" title="Show Alert" onclick={showAlertError}>
    </lightning-button>
    <lightning-button label="Show Warning Alert" title="Show Alert" onclick={showAlertWarning}>
    </lightning-button>
</template>

To make the lighting component visible to the lighting pages, enter the code below in the meta.xml file inside the LightningComponentBundle tag.

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

To deploy the Lightning Web Component, navigate to the lightning page and click on the settings icon, then select Edit page.

In the Lightning App Builder, add the Lightning Web Component to the page by dragging and dropping it, then save the changes.

Now, in the Lighting web component, you will see buttons for alert notifications of success, error, and warning.

Alert success notification:

How to add alert notification in LWC

Alert error notification:

Display erroe alert in Salesforce LWC

Alert warning notification:

Add warning alert in Lightning Web Components

This way, we can add alert notifications in the Salesforce Lightning Web Components.

Use Lightning Prompt in Salesforce Lightning Web Components

In Salesforce, the Lightning Prompt modal enables us to create a prompt modal within the Lightning Web Component, which is used to request that the user provide information before proceeding.

Let’s take an example, where we will use a lightning prompt in the login form. The user will enter their email and password, then click the Proceed button.

As the user clicks the button, a prompt will appear in the Lightning Web Component asking to enter the OTP in the input field.

Create the Lightning Web Component ‘promptModal‘ and enter the code below in the JS file.

To use the Lightning prompt module, we have used the import method [import LightningPrompt from ‘lightning/prompt’].

import { LightningElement } from 'lwc';
import LightningPrompt from 'lightning/prompt';
 
export default class PromptModal extends LightningElement {
    username = "";
    password = "";
 
    handleUsernameChange(event){
        this.username = event.target.value;
    } 
 
    handlePasswordChange(event){
        this.password = event.target.value;
    } 
 
    handleCancel() {
    }
 
    async handleProceed(){
        const result = await LightningPrompt.open({ 
                message: 'Enter the OTP', 
                theme: 'warning', 
                label: 'Please Answer!', 
                variant: 'header', 
                defaultValue: '', 
        });
    }
}

The logic to display the lighting prompt is handled in the handleProceed() that will open the prompt using LightningPrompt.open(), and here we have defined the parameters of the lighting prompt in properties message, theme, label, and variant.

To define the UI of the login form in the Lightning Web Component, enter the code below in the promptModal.html file.

<template>
    <lightning-card title="Lightning Prompt">
        <div class="slds-box slds-theme_default">
            <lightning-input 
                    type="email" 
                    label="Username"
                    value={username}
                    onchange={handleUsernameChange}>
            </lightning-input>
            <lightning-input 
                    type="password" 
                    label="Password"
                    value={password}
                    onchange={handlePasswordChange}>
            </lightning-input>
            <div class="slds-m-top_small slds-align_absolute-center">
                <lightning-button 
                    variant="brand" 
                    label="Proceed" 
                    class="slds-m-left_x-small" 
                    onclick={handleProceed}>
                </lightning-button>
                <lightning-button 
                    variant="brand-outline" 
                    class="slds-m-left_x-small" 
                    label="Cancel" 
                    onclick={handleCancel}>
                </lightning-button>
            </div>
        </div>
    </lightning-card>
</template>

Make the component visible on Lightning pages by using the code below in the meta.xml file.

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

Now, deploy the Lightning Web Component to the Lightning page, and there you will see the login form. Enter the details in the form and click the Proceed button.

display a input prompt in Lightning Web components

So, this is how we can use the Lightning Prompt in Salesforce Lightning web component and take user inputs in an alert window.

Use Lightning Confirm in Salesforce Lightning Web Component

In Salesforce Lightning Web Components (LWC), we use LightningConfirm to display a confirmation dialog before performing important actions, such as deleting a record, submitting a form, or making irreversible changes.

It helps ensure that users intentionally approve an action, reducing the risk of mistakes. In this example, we’ll see how to use LightningConfirm to ask the user for confirmation before deleting a record.

Now, follow the steps below to create a Lightning web component that displays a confirmation alert on the screen before deleting records.

In this example, we will create an LWC that allows a user to reset a username and password in input fields.

When the user clicks the “Proceed” button, a confirmation pop-up appears asking if they are sure they want to reset the fields. If the user confirms, the component automatically resets the username field to a default email.

  1. Create a Lightning Web Component with label lightningConfirmNotification and enter the below code in the HTML file to define the UI of the LWC.
<template>
    <lightning-card title="Lightning Confirm">
        <div class="slds-box slds-theme_default">
            <lightning-input 
                    type="email" 
                    label="Username"
                    value={username}
                    onchange={handleUsernameChange}>
            </lightning-input>
            <lightning-input 
                    type="password" 
                    label="Password"
                    value={password}
                    onchange={handlePasswordChange}>
            </lightning-input>
            <div class="slds-m-top_small slds-align_absolute-center">
                <lightning-button 
                    variant="brand" 
                    label="Proceed" 
                    class="slds-m-left_x-small" 
                    onclick={handleProceed}>
                </lightning-button>
                <lightning-button 
                    variant="brand-outline" 
                    class="slds-m-left_x-small" 
                    label="Cancel" 
                    onclick={handleCancel}>
                </lightning-button>
            </div>
        </div>
    </lightning-card>
</template>

In this HTML template, we have defined input fields to enter the password and the username

  1. For the logic to display confirmation message by calling {handleProceed} enter the code below in the JS file.

To display a confirm notification, we have used the imported LightningConfirm module with the method import LightningConfirm from ‘lightning/confirm’.

import { LightningElement } from 'lwc';
import LightningConfirm from 'lightning/confirm';

export default class LightningConfirmNotification extends LightningElement {
    username = "";
    password = "";

    handleUsernameChange(event){
        this.username = event.target.value;
    } 

    handlePasswordChange(event){
        this.password = event.target.value;
    } 

    handleCancel() {
    }

    async handleProceed(){
        const result = await LightningConfirm.open({
            message: 'Are you sure you want to reset fields?',
            variant: 'header',
            label: 'Please Confirm',
            theme: 'error',
        });

        if(result==true){
            this.username = "admin@mail.com";
            this.password = "***********";

        }
    }
}

We have defined the event handleProceed to open a confirmation window that will trigger when the user presses the proceed button. In this, we have defined three properties: message, variant, label, and theme.

Here, message is the text that you will see in the text that will appeat in the confirmation window. We have selected the theme as “error” to show red color in the confirmation window.

  1. Enter the code below in the meta.html file to make the component visible to the Lightning pages.
<isExposed>true</isExposed>
    <targets>
        <target>lightning__AppPage</target>
        <target>lightning__RecordPage</target>
        <target>lightning__HomePage</target>
    </targets>

After this, deploy the Lightning web component to the Lightning page, and then you will see the UI where we can enter the username and password.

Add Lightinng Confirm notification in LWC

After entering the details in the input fields, as we click the proceed button, the confirmation message will appear on the screen as shown below.

Lighting Confirm notification In Salesforce LWC

This way, we can utilize the Lightning Confirm module to display confirmation messages within Lightning web components.

Conclusion

In this Salesforce tutorial, we learned how to show different types of notifications in Salesforce Lightning Web Components using LightningAlert, LightningPrompt, and LightningConfirm. These built-in modules enable us to alert users, request their input, or confirm important actions.

I hope the above examples helped you understand how to add alerts, prompts, and confirm messages in Lightning Web Components.

You may also like to read:

Agentforce in Salesforce

DOWNLOAD FREE AGENTFORCE EBOOK

Start with AgentForce in Salesforce. Create your first agent and deploy to your Salesforce Org.

Salesforce flows complete guide

FREE SALESFORCE FLOW EBOOK

Learn how to work with flows in Salesforce with 5 different real time examples.