ABSYZ ABSYZ

  • Home

    Home

  • About us

    Who We Are

  • Our Expertise

    What we Do

  • Our Approach

    How We Do It

  • Products

    What We Made

  • Industries

    Who We Do It For

  • Clients

    Whom We Did It For.

  • Article & Blogs

    What Experts Think

  • Careers

    Join The Team

  • Get In Touch

    Let’s Get Started

ABSYZ

Using Modal/ Popup in Lightning Web Components

Home / Article & Blogs / Salesforce / Lightning / Using Modal/ Popup in Lightning Web Components
By abhishekkumar915 inLightning, Lightning Web Components

In this blog, we will be learning to use Modal/ Popup in Lightning Web Component. We will be using SLDS classes that helps in showing or hiding the Modal.

The below classes help in showing and hiding of the modal

 

  1. slds-fade-in-open – Shows the modal
  2. slds-backdrop_open – Shows the backdrop(greyed out)

So, adding and removing these classes at an action will show/ hide the modal accordingly.

In this example, we will be making a Modal component and show the data required by checking the sObject of the current record page it is being used. So, this component can be used at any sObject record page, and the required server call can be performed.

Let’s have a look at the components.

 

Apex Class

Modal_LWC_controller.cls
This class checks the sObject type and calls the function required for that sObject

 

/**
* @File Name          : Modal_LWC_controller.cls
* @Description        : 
* @Author             : Abhishek Kumar
* @Group              : 
* @Last Modified By   : abhishek.kumar@absyz.com
* @Modification Log   : 
* Ver       Date            Author      		    Modification
* 1.0    19/10/2019   	Abhishek Kumar     				1.0
**/
public with sharing class Modal_LWC_controller {
    
    @AuraEnabled(cacheable=true)
    public static WrapperClass fetchWrapperData(Id sObjectId){
        WrapperClass wrapperClassVar = new WrapperClass();
        if(sObjectId.getSobjectType() == Schema.Account.SObjectType){
            wrapperClassVar.contactList = Modal_LWC_controller.getRelatedContacts(sObjectId);
        }else if(sObjectId.getSobjectType() == Schema.Contact.SObjectType){
            wrapperClassVar.accId = Modal_LWC_controller.getAccId(sObjectId);
        }
        System.debug('wrapperClassVar-->>'+wrapperClassVar);
        return wrapperClassVar;
    }
    
    public static List<Contact> getRelatedContacts(String accId){
        return [SELECT Id, Name, Phone, Email FROM Contact WHERE AccountId =:accId];
    }
        
    public static String getAccId(String contactId) {
        return [SELECT Id, AccountId FROM Contact WHERE Id=:contactId].AccountId; 
    }
    
    public class WrapperClass {
        @AuraEnabled
        public List<Contact> contactList {get; set;}
        @AuraEnabled
        public Id accId{get; set;}
        
        public wrapperClass() {
            this.contactList = new List<Contact>();
        }
    }
}

 

LWC Components

modal_LWC.html

 

<!--
  @File Name          : modal_LWC.html
  @Description        : 
  @Author             : Abhishek Kumar
  @Group              : 
  @Last Modified By   : abhishek.kumar@absyz.com
  @Modification Log   : 
  Ver       Date            Author      		    Modification
  1.0    19/10/2019     Abhishek Kumar                  1.0
-->
<template>
    <lightning-button variant="brand" label={btnLabel} title={btnLabel} onclick={openModal} class="slds-m-left_x-small"></lightning-button>
    <section role="dialog" tabindex="-1" aria-labelledby="modal-heading-01" aria-modal="true" aria-describedby="modal-content-id-1" class={modalClass}>
    <div class="slds-modal__container">
        <header class="slds-modal__header">
        <h2 id="modal-heading-01" class="slds-modal__title slds-hyphenate">{modalHeader}</h2>
        </header>
        <div class="slds-modal__content slds-p-around_medium" id="modal-content-id-1">
            <template if:true={isContact}>
                <lightning-record-view-form
                    record-id={accountId}
                    object-api-name="Account">
                    <div class="slds-grid">
                        <div class="slds-col slds-size_1-of-2">
                            <lightning-output-field field-name="Name"></lightning-output-field>
                            <lightning-output-field field-name="Website"></lightning-output-field>
                        </div>
                        <div class="slds-col slds-size_1-of-2">
                            <lightning-output-field field-name="Potential_Value__c"></lightning-output-field>
                            <lightning-output-field field-name="Most_Recent_Closed_Date__c"></lightning-output-field>
                        </div>
                    </div>
                </lightning-record-view-form>
            </template>
            <template if:false={isContact}>
                <div class="slds-border_left slds-border_right slds-border_top">                    
                    <lightning-datatable
                        key-field="id"
                        data={contactList}
                        show-row-number-column
                        row-number-offset={rowOffset}
                        hide-checkbox-column
                        resize-column-disabled
                        columns={columns}>
                    </lightning-datatable>
                </div>
            </template>
        </div>
        <footer class="slds-modal__footer">
        <button class="slds-button slds-button_neutral" onclick={closeModal}>Cancel</button>
        <button class="slds-button slds-button_brand" disabled>Save</button>
        </footer>
    </div>
    </section>
    <div class={modalBackdropClass}></div>
    
    </template>

modal_LWC.js

 

import { LightningElement, track, api } from 'lwc';
import { ShowToastEvent } from 'lightning/platformShowToastEvent'
import fetchWrapperData from '@salesforce/apex/Modal_LWC_controller.fetchWrapperData';

const columns = [
  { label: 'Name', fieldName: 'Name' },
  { label: 'Email', fieldName: 'Email', type: 'email' },
  { label: 'Phone', fieldName: 'Phone', type: 'phone' }
];

export default class Modal_LWC extends LightningElement {
  @track columns = columns;   
  @track accountId; 
  @track contactList;
  @track rowOffset = 0;
  @track error;   
  @track btnLabel = '';   
  @track modalHeader = '';
  @track isContact = false;
  @track modalClass = 'slds-modal ';
  @track modalBackdropClass = 'slds-backdrop ';
  @api recordId;  //Stores recordId
  @api objectApiName;   //Stores the current object API Name

  connectedCallback() {   //doInit() function, Dynamically changing the modal header and button label as per sObject, and also assigning the isContact property as per sObject
    if(this.objectApiName === 'Account'){
      this.isContact = false;
      this.modalHeader = 'Related Contacts';
      this.btnLabel = 'See Related Contacts';
    }else if(this.objectApiName === 'Contact'){
      this.isContact = true;
      this.modalHeader = 'Account Details';
      this.btnLabel = 'See Account Details';
    }
  }

  //Adds the classes that shows the Modal and does server calls to show the required data
  openModal() {
    this.modalClass = 'slds-modal slds-fade-in-open';
    this.modalBackdropClass = 'slds-backdrop slds-backdrop_open';
    fetchWrapperData({sObjectId: this.recordId})
      .then(result => {    //Returns the wrapper 
        if(result.accId != null){
          this.accountId = result.accId;
          this.isContact = true;
        }else{
          this.contactList = result.contactList;
          this.isContact = false;
        }
      })
      .catch(error => {
        const event = new ShowToastEvent({
          title: 'Error Occured',
          message: 'Error: '+error.body.message,
          variant: 'error'
         });
        this.dispatchEvent(event);    //To show an error Taost if error occurred while the APEX call
        });
  }

  //Removes the classes that hides the Modal
  closeModal() {
    this.modalClass = 'slds-modal ';
    this.modalBackdropClass = 'slds-backdrop ';
  }
}

Alternatively, we can use <template if:false> for showing/ hiding the modal without changing the classes.

So as mentioned in the above components, this component is being used on Account and Contact record pages. Let us see how it looks on both of them.

Account Record Page:

On clicking the button, ‘See Related Contacts’, it queries the contacts under the account and displays that.

 

Contact Record Page:

On clicking the button, ‘See Account Details’, it fetches the related Account details and displays the fields mentioned.

 

 

Clicking the ‘Cancel’ button, closes the Modal/ Popup.
Similarly, this component can be used to show required data in the Modal as per the sObject using this on the record page.

 

SalesforceSFDC
153
Like this post
1 Post
abhishekkumar915

Search Posts

Archives

Categories

Recent posts

BioAsia 2023 in Hyderabad: An Annual International Event

BioAsia 2023 in Hyderabad: An Annual International Event

The Role Of Marketing in Small & Medium Enterprises

The Role Of Marketing in Small & Medium Enterprises

Salesforce For Retail: How Salesforce CRM Can Help Retailers

Salesforce For Retail: How Salesforce CRM Can Help Retailers

What is ChatGPT & How Does It Work?

What is ChatGPT & How Does It Work?

What Is Graphic Design? (Executive Summary 2023)

What Is Graphic Design? (Executive Summary 2023)

  • Previous PostSalesforce integration with Paypal
  • Next PostPardot: Jogging your memory on the basics.

Related Posts

Difference Between Aura and LWC
Lightning Web Components Salesforce

Difference Between Aura and LWC

How To Use Navigation And Toast Messages in LWC Inside Visualforce Page?
Lightning Web Components Salesforce

How To Use Navigation And Toast Messages in LWC Inside Visualforce Page?

How To Read Excel Data Using LWC Salesforce?
Lightning Web Components Salesforce

How To Read Excel Data Using LWC Salesforce?

Why Do We Use Lightning in Salesforce?
Lightning Salesforce

Why Do We Use Lightning in Salesforce?

Leave a Reply (Cancel reply)

Your email address will not be published. Required fields are marked *

*
*

ABSYZ Logo

INDIA | USA | UAE

  • About us
  • Article & Blogs
  • Careers
  • Get In Touch
  • Our Expertise
  • Our Approach
  • Products
  • Industries
  • Clients
  • White Papers

Copyright ©2022 Absyz Inc. All Rights Reserved.

youngsoft
Copy
We use cookies on our website to give you the most relevant experience by remembering your preferences and repeat visits. By clicking “ACCEPT ALL”, you consent to the use of ALL the cookies. However, you may visit "Cookie Settings" to provide a controlled consent. Privacy Policy
Cookie SettingsREJECT ALLACCEPT ALL
Manage consent

Privacy Overview

This website uses cookies to improve your experience while you navigate through the website. Out of these, the cookies that are categorized as necessary are stored on your browser as they are essential for the working of basic functionalities of the website. We also use third-party cookies that help us analyze and understand how you use this website. These cookies will be stored in your browser only with your consent. You also have the option to opt-out of these cookies. But opting out of some of these cookies may affect your browsing experience.
Necessary
Always Enabled

Necessary cookies are absolutely essential for the website to function properly. These cookies ensure basic functionalities and security features of the website, anonymously.

CookieDurationDescription
cookielawinfo-checkbox-analytics11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Analytics".
cookielawinfo-checkbox-functional11 monthsThe cookie is set by GDPR cookie consent to record the user consent for the cookies in the category "Functional".
cookielawinfo-checkbox-necessary11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookies is used to store the user consent for the cookies in the category "Necessary".
cookielawinfo-checkbox-others11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Other.
cookielawinfo-checkbox-performance11 monthsThis cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Performance".
viewed_cookie_policy11 monthsThe cookie is set by the GDPR Cookie Consent plugin and is used to store whether or not user has consented to the use of cookies. It does not store any personal data.

Functional

Functional cookies help to perform certain functionalities like sharing the content of the website on social media platforms, collect feedbacks, and other third-party features.

Performance

Performance cookies are used to understand and analyze the key performance indexes of the website which helps in delivering a better user experience for the visitors.

Analytics

Analytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics the number of visitors, bounce rate, traffic source, etc.

Advertisement

Advertisement cookies are used to provide visitors with relevant ads and marketing campaigns. These cookies track visitors across websites and collect information to provide customized ads.

Others

Other uncategorized cookies are those that are being analyzed and have not been classified into a category as yet.

SAVE & ACCEPT