Add Confirmation, Alert and Prompt Dialog Box to Lightning Web Component

Add Confirmation, Alert and Prompt Dialog Box to Lightning Web Component

Last Updated on November 23, 2022 by Rakesh Gupta

Big Idea or Enduring Question:

  • How to display alert, confirmation, or prompt using the lightning web component when performing specific actions? 

Objectives:

After reading this blog, you’ll be able to:

  • Understand the difference between alert, confirmation, or prompt model dialog 
  • Add an alert modal within your lightning web component
  • Add a confirmation modal within your lightning web component
  • Add a prompt modal within your lightning web component
  • Track the result of user action for model dialog 
  • and much more

In the past written a few articles on Lightning Web Component. Why not check them out while you are at it?! 

  1. How to Implement Conditional Rendering in Lightning Web Component
  2. Pass lightning-input field Value from a Button Click to Lightning Web Component Controller
  3. Reset lightning-input Field on Button Click in Lightning Web Component

Business Use case

Rachel Gillett is working as a Junior Developer at Gurukul on Cloud (GoC). So far, she has created this form, learned how to pass user-entered values to the lightning web component controller, and reset the input fields when a user clicks on the cancel button, as shown below:

Now she wants to provide an ability to review their cancel button action by displaying a confirmation pop-up as shown below. If users select the OK button, then reset the input field value; otherwise, don’t take any action. 

Alert Notification Box

The alert popup box is basically used to popup a message or a warning for the user. The primary purpose of the alert function is to display a message to the user containing any critical information.

Use LightningAlert on your components to communicate a state that affects the entire system, not just a feature or page. LightningAlert.open() doesn’t halt execution on the page; it returns a Promise. Use async/await or .then() for any code you want to execute after the alert has closed.

Import LightningAlert from the lightning/alert module in the component that will launch the alert modal, and call LightningAlert.open() with your desired attributes.

The above example creates an alert modal with an error message and an OK button. The .open() function returns a promise that resolves when the user clicks OK.

<!-- lighntingInputExample.html -->
<template>
    <form>
        <div
            class="slds-p-top_small slds-p-bottom_medium slds-align_absolute-center slds-theme_default slds-text-heading_medium">
            <b>Lightning-Input Example</b></div>
        <div class="slds-box slds-theme_default">
            <lightning-input 
                    type="email" 
                    label="Email Address"
                    value={emailvalue}
                    onchange={handleEmailChange}>
            </lightning-input>
            <lightning-input 
                    type="tel" 
                    name="mobile"
                    label="Mobile"
                    value={mobilevalue}
                    onchange={handleMobileChange}>
            </lightning-input>
            <div class="slds-m-top_small slds-align_absolute-center">
                <lightning-button 
                    variant="Neutral" 
                    label="Cancel" 
                    class="slds-m-left_x-small" 
                    onclick={handleCancel}>
                </lightning-button>
                <lightning-button 
                    variant="brand" 
                    class="slds-m-left_x-small" 
                    label="Next" 
                    onclick={handleNext}>
                </lightning-button>
            </div>
        </div>
    </form>
</template>

//lighntingInputExample.js
import { LightningElement } from 'lwc';
import LightningAlert from 'lightning/alert';

export default class InputExample extends LightningElement() {

    emailvalue ="username@example.com";
    mobilevalue= "000-000-0000";

    handleEmailChange(event){
        this.emailvalue = event.target.value;
    } 

    handleMobileChange(event){
        this.mobilevalue = event.target.value;
    } 

    handleNext() {
        
    }

    async handleCancel(){

            await LightningAlert.open({
            message: 'this is the alert message',
            theme: 'error', 
            label: 'Error!', 
            variant: 'header',
        });
    }
}

Prompt Notification Box

The prompt popup box is a way to display a message and get data from the user. The prompt box is used to get a single data from the user, which might be used to perform tasks based on the answer. The prompt box can be used for tasks like asking the name of the user or age, gender, etc.

The lightning/prompt module lets you create a prompt modal within your component. Use LightningPrompt on your components to ask the user to provide information before continuing.

Import LightningPrompt from the lightning/prompt module in the component that will launch the prompt modal, and call LightningPrompt.open() with your desired attributes.

This example creates a prompt modal with a header, message, and two buttons. If the user enters text and clicks OK in the prompt, the .open() function returns a promise that resolves to the input value. If the user clicks Cancel, the function returns a promise that resolves to null.

<!-- lighntingInputExample.html -->
<template>
    <form>
        <div
            class="slds-p-top_small slds-p-bottom_medium slds-align_absolute-center slds-theme_default slds-text-heading_medium">
            <b>Lightning-Input Example</b></div>
        <div class="slds-box slds-theme_default">
            <lightning-input 
                    type="email" 
                    label="Email Address"
                    value={emailvalue}
                    onchange={handleEmailChange}>
            </lightning-input>
            <lightning-input 
                    type="tel" 
                    name="mobile"
                    label="Mobile"
                    value={mobilevalue}
                    onchange={handleMobileChange}>
            </lightning-input>
            <div class="slds-m-top_small slds-align_absolute-center">
                <lightning-button 
                    variant="Neutral" 
                    label="Cancel" 
                    class="slds-m-left_x-small" 
                    onclick={handleCancel}>
                </lightning-button>
                <lightning-button 
                    variant="brand" 
                    class="slds-m-left_x-small" 
                    label="Next" 
                    onclick={handleNext}>
                </lightning-button>
            </div>
        </div>
    </form>
</template>

//lighntingInputExample.js
import { LightningElement } from 'lwc';
import LightningPrompt from 'lightning/prompt';

export default class InputExample extends LightningElement() {

    emailvalue ="username@example.com";
    mobilevalue= "000-000-0000";

    handleEmailChange(event){
        this.emailvalue = event.target.value;
    } 

    handleMobileChange(event){
        this.mobilevalue = event.target.value;
    } 

    handleNext() {
        
    }

    async handleCancel(){

    const result = await LightningPrompt.open({ 
            message: 'What is your gender?', 
            theme: 'warning', 
            label: 'Please Answer!', 
            variant: 'header', 
            defaultValue: '', 
    }); 
        if(result=='male'){ 
            //add logic for male 
        } 
        else if (result=='female'){ 
         // add logic for female 
        } 
        else{ 
            //logic for remaining 
        }
    }
}

Automation Champion Approach (I-do):

Now let’s return to our original use case, where Rachel wants to provide an ability to review their cancel button action by displaying a confirmation pop-up. If users select the OK button, then reset the input field value; otherwise, don’t take any action. Before going ahead, let’s spend a few minutes understanding a confirmation notification box and how to implement it in the lightning web component controller. 

Confirmation Notification Box

The confirm popup box displays a message to the users asking for their confirmation to proceed with an event they have triggered. An example of the confirm box would be the popup on the user’s browser to confirm their action.

The confirm popup box allows users to choose by providing users with a two-button option. When users click the button, the task linked to the clicked button is performed. The two buttons which the confirm box provides are OK and Cancel.

lightningInputExample.js-meta.xml

A lightning web component can be used to build custom pages for Lightning Experience and the Salesforce mobile app quickly with point-and-click tools. Make sure to add the right target for it. 

This configuration file makes the component available for all Lightning page types but restricts support on desktops.

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>54.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
        <target>lightning__RecordPage</target>
        <target>lightning__AppPage</target>
        <target>lightning__HomePage</target>
    </targets>
</LightningComponentBundle>

lightningInputExample.html

Every UI component must have an HTML file with the root tag <template>. The template contains two lightning-input tags that create input for email and mobile. The template includes two lightning-buttonThe first button (Next) is used to pass the value to JavaScript Component, whereas the second button (Cancel) is used to reset the input fields.

When a user clicks on the Cancel button will call a JavaScript method handleCancel() which will use LightningConfirm.open() that will launch the confirm modal.

<!-- lighntingInputExample.html -->
<template>
    <form>
        <div
            class="slds-p-top_small slds-p-bottom_medium slds-align_absolute-center slds-theme_default slds-text-heading_medium">
            <b>Lightning-Input Example</b></div>
        <div class="slds-box slds-theme_default">
            <lightning-input 
                    type="email" 
                    label="Email Address"
                    value={emailvalue}
                    onchange={handleEmailChange}>
            </lightning-input>
            <lightning-input 
                    type="tel" 
                    name="mobile"
                    label="Mobile"
                    value={mobilevalue}
                    onchange={handleMobileChange}>
            </lightning-input>
            <div class="slds-m-top_small slds-align_absolute-center">
                <lightning-button 
                    variant="Neutral" 
                    label="Cancel" 
                    class="slds-m-left_x-small" 
                    onclick={handleCancel}>
                </lightning-button>
                <lightning-button 
                    variant="brand" 
                    class="slds-m-left_x-small" 
                    label="Next" 
                    onclick={handleNext}>
                </lightning-button>
            </div>
        </div>
    </form>
</template>

lightningInputExample.js

This JavaScript controller creates a confirm modal with two buttons, OK and Cancel. The .open() function returns a promise that resolves to true (and reset input fields) when a user clicks OK and false (do nothing) when the user clicks Cancel.

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

export default class InputExample extends LightningElement() {

    emailvalue ="username@example.com";
    mobilevalue= "000-000-0000";

    handleEmailChange(event){
        this.emailvalue = event.target.value;
    } 

    handleMobileChange(event){
        this.mobilevalue = event.target.value;
    } 

    handleNext() {

        alert('email '+ this.emailvalue);
        alert('Mobile '+ this.mobilevalue);
        
    }
    async handleCancel(){

        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.emailvalue = "username@example.com";
            this.mobilevalue = "000-000-0000";

        }
    }
}

Proof of Concept

Formative Assessment:

I want to hear from you!

What is one thing you learned from this post? How do you envision applying this new knowledge in the real world? Feel free to share in the comments below.

Have feedback, suggestions for posts, or need more information about Salesforce online training offered by me? Say hello, and leave a message!

5 thoughts on “Add Confirmation, Alert and Prompt Dialog Box to Lightning Web Component

  1. Thanks for sharing this detailed & specific info, as I am in my starting phase of learning LWC , but still with your detailed information I am able to understand each & every point. Thank you 🙂

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.