+ Start a Discussion
KMK91KMK91 

How to create popup in lightning

Hi,
Page which will display all accounts in the org, there should be one button for Add Account. On click of this button, popup will ask for account details (Mandatory details only) and after click on submit button this new account will add to DB, go to previous page and previous page also will refresh.




Thanks
KMK
Best Answer chosen by KMK91
Khan AnasKhan Anas (Salesforce Developers) 
Hi,

Greetings to you!

Below is the sample code which I have tested in my org and it is working fine. Kindly modify the code as per your requirement.

Component:
<aura:component controller="PopupFormC"
                implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction" access="global" >
    
    <aura:attribute name="PageHeading" type="String" default="MODAL POPUP" />
    <aura:attribute name="mydata" type="List"/>
    <aura:attribute name="accdata" type="List"/>
    <aura:attribute name="mydata1" type="List"/>
    <aura:attribute name="accForm" type="Account" default="{'sobjectType' : 'Account'}"/>
    
    <aura:handler name="init" value="{!this}" action="{!c.doinit}" />
    <aura:handler event="force:refreshView" action="{!c.doinit}" />
    
    <div class="slds-m-top--xx-large">
        <div class="slds-page-header">
            <div class="slds-align--absolute-center">
                <div class="slds-text-heading--large">       
                    {!v.PageHeading}
                </div>
            </div>
        </div>
    </div>
    <br/> <br/>
    
    <lightning:button label="Create Account PopUp"
                      iconName="utility:new_window"
                      iconPosition="left"
                      variant="brand"
                      onclick="{!c.newPopup}"
                      />
    
    <div role="dialog" tabindex="-1" aria-labelledby="header43" aura:id="Modalbox1" class="slds-modal slds-modal_large">
        <div class="slds-modal__container" style="width: 65%;">
            <div class="slds-modal__header">
                ACCOUNT
            </div>
            
            <div class="slds-modal__content slds-p-around--medium">
                <div class="slds-p-left_xx-large slds-p-right_xx-large">
                    <div class="slds-page-header" style="padding-top: 9px; padding-bottom: 9px;, padding-right: 9px;, padding-left: 10px;">
                        <h3 style="font-size: 1rem;" title="">Account Information</h3>
                    </div> 
                </div>    
                <div class="slds-grid slds-p-top_medium">
                    <div class="slds-size_6-of-12 slds-p-left_xx-large slds-p-horizontal_x-large " >
                        <lightning:input label="Account Name" name="myname" value="{!v.accForm.Name}"/> 
                    </div>
                    <div class="slds-size_5-of-12 slds-p-left_xx-small slds-p-horizontal_x-large " >
                        <lightning:input label="Phone" name="myname" value="{!v.accForm.Phone}"/> 
                    </div>
                </div>
                <div class="slds-grid slds-p-top_x-small">
                    <div class="slds-size_6-of-12 slds-p-left_xx-large slds-p-horizontal_x-large " >
                        <lightning:input label="Account Number" name="mynumber" value="{!v.accForm.AccountNumber}"/> 
                    </div>
                    <div class="slds-size_5-of-12 slds-p-left_xx-small slds-p-horizontal_x-large " >
                        <lightning:input label="Description" name="myphone" value="{!v.accForm.Description}"/> 
                    </div>
                </div>
            </div>
            <div class="slds-modal__footer">
                <lightning:button label="Save" onclick="{!c.saveModal}" />
                <lightning:button label="close" onclick="{!c.closeNewModal}" />
            </div>
        </div>
    </div>
    
    
    <div class="slds-section slds-is-open">
        <h3 class="slds-section__title slds-theme_shade">
            <span class="slds-truncate slds-p-horizontal_small" title="Section Title">Accounts</span>
        </h3>
        <br/>
        <table class="slds-table slds-table--bordered slds-table--striped slds-table--cell-buffer slds-table--fixed-layout">
            <thead>
                <tr class="slds-text-heading--label">
                    <th scope="col"><div class="slds-truncate" title="Account Name">Account Name</div></th>
                    <th scope="col"><div class="slds-truncate" title="Phone">Phone</div></th>
                </tr>
            </thead>
            <tbody>
                <aura:iteration items="{!v.mydata}" var="row" indexVar="index">
                    <tr>
                        <th scope="row"><div class="slds-truncate" title="{!row.Name}">{!row.Name}</div></th>
                        <td><div class="slds-truncate" title="{!row.Phone}">{!row.Phone}</div></td>
                    </tr>
                </aura:iteration>
            </tbody>
        </table>
    </div>
</aura:component>

Controller:
({
    doinit : function(component, event, helper) {
        var action = component.get('c.fetchAcc');
        action.setCallback(this, function(response){
            var state = response.getState();
            if(state === "SUCCESS"){
                var allValues = response.getReturnValue();
                console.log("allValues--->>> " + allValues);
                component.set('v.mydata', allValues);
            }
            else if(state === "ERROR") {
                var errors = response.getError();
                if(errors){
                    if(errors[0] && errors[0].message){
                        console.log("Error Message: " + errors[0].message);
                    }
                }
                else{
                    console.log("Unknown Error");
                }
            }
        });
        $A.enqueueAction(action);
    },
    
    newPopup : function(component, event, helper){
        var cmpTarget = component.find('Modalbox1');
        var cmpBack = component.find('Modalbackdrop');
        $A.util.addClass(cmpTarget, 'slds-fade-in-open');
        $A.util.addClass(cmpBack, 'slds-backdrop--open');
    },
    
    saveModal : function(component, event, helper){
        var regForm = component.get("v.accForm");
        var action = component.get("c.saveDetails");
        action.setParams({regForm1  : regForm});
        action.setCallback(this, function(response) {
            var state = response.getState();          
            if (state === "SUCCESS") {
                $A.get('e.force:refreshView').fire();
                var cmpTarget = component.find('Modalbox1');
                var cmpBack = component.find('Modalbackdrop');
                $A.util.removeClass(cmpBack,'slds-backdrop--open');
                $A.util.removeClass(cmpTarget, 'slds-fade-in-open');
                
            }
            else if (state === "ERROR") {
                var errors = response.getError();
                if (errors) {
                    if (errors[0] && errors[0].message) {
                        console.log("Error message: " + 
                                    errors[0].message);
                    }
                } 
                else {
                    console.log(response.getReturnValue());
                }
            }
        });
        $A.enqueueAction(action);
    },
    
    closeNewModal : function(component, event, helper){
        var cmpTarget = component.find('Modalbox1');
        var cmpBack = component.find('Modalbackdrop');
        $A.util.removeClass(cmpBack,'slds-backdrop--open');
        $A.util.removeClass(cmpTarget, 'slds-fade-in-open');
    },
})

CSS:
.THIS {
}

.THIS .slds-section__title{
    background-color: YellowGreen;
    color: white
}
.THIS .slds-modal__header{
    background-color: OliveDrab;
    color: white
}

Apex:
public class PopupFormC {

    @AuraEnabled
    public static List<Account> fetchAcc (){
        return [SELECT Id, Name, Phone FROM Account ORDER BY CreatedDate desc];
    }

	@AuraEnabled
    public static void saveDetails (Account regForm1){ 
    	INSERT regForm1;
    }
}


I hope it helps you.

Kindly let me know if it helps you and close your query by marking it as solved so that it can help others in the future.

Thanks and Regards,
Khan Anas

All Answers

Khan AnasKhan Anas (Salesforce Developers) 
Hi,

Greetings to you!

Below is the sample code which I have tested in my org and it is working fine. Kindly modify the code as per your requirement.

Component:
<aura:component controller="PopupFormC"
                implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction" access="global" >
    
    <aura:attribute name="PageHeading" type="String" default="MODAL POPUP" />
    <aura:attribute name="mydata" type="List"/>
    <aura:attribute name="accdata" type="List"/>
    <aura:attribute name="mydata1" type="List"/>
    <aura:attribute name="accForm" type="Account" default="{'sobjectType' : 'Account'}"/>
    
    <aura:handler name="init" value="{!this}" action="{!c.doinit}" />
    <aura:handler event="force:refreshView" action="{!c.doinit}" />
    
    <div class="slds-m-top--xx-large">
        <div class="slds-page-header">
            <div class="slds-align--absolute-center">
                <div class="slds-text-heading--large">       
                    {!v.PageHeading}
                </div>
            </div>
        </div>
    </div>
    <br/> <br/>
    
    <lightning:button label="Create Account PopUp"
                      iconName="utility:new_window"
                      iconPosition="left"
                      variant="brand"
                      onclick="{!c.newPopup}"
                      />
    
    <div role="dialog" tabindex="-1" aria-labelledby="header43" aura:id="Modalbox1" class="slds-modal slds-modal_large">
        <div class="slds-modal__container" style="width: 65%;">
            <div class="slds-modal__header">
                ACCOUNT
            </div>
            
            <div class="slds-modal__content slds-p-around--medium">
                <div class="slds-p-left_xx-large slds-p-right_xx-large">
                    <div class="slds-page-header" style="padding-top: 9px; padding-bottom: 9px;, padding-right: 9px;, padding-left: 10px;">
                        <h3 style="font-size: 1rem;" title="">Account Information</h3>
                    </div> 
                </div>    
                <div class="slds-grid slds-p-top_medium">
                    <div class="slds-size_6-of-12 slds-p-left_xx-large slds-p-horizontal_x-large " >
                        <lightning:input label="Account Name" name="myname" value="{!v.accForm.Name}"/> 
                    </div>
                    <div class="slds-size_5-of-12 slds-p-left_xx-small slds-p-horizontal_x-large " >
                        <lightning:input label="Phone" name="myname" value="{!v.accForm.Phone}"/> 
                    </div>
                </div>
                <div class="slds-grid slds-p-top_x-small">
                    <div class="slds-size_6-of-12 slds-p-left_xx-large slds-p-horizontal_x-large " >
                        <lightning:input label="Account Number" name="mynumber" value="{!v.accForm.AccountNumber}"/> 
                    </div>
                    <div class="slds-size_5-of-12 slds-p-left_xx-small slds-p-horizontal_x-large " >
                        <lightning:input label="Description" name="myphone" value="{!v.accForm.Description}"/> 
                    </div>
                </div>
            </div>
            <div class="slds-modal__footer">
                <lightning:button label="Save" onclick="{!c.saveModal}" />
                <lightning:button label="close" onclick="{!c.closeNewModal}" />
            </div>
        </div>
    </div>
    
    
    <div class="slds-section slds-is-open">
        <h3 class="slds-section__title slds-theme_shade">
            <span class="slds-truncate slds-p-horizontal_small" title="Section Title">Accounts</span>
        </h3>
        <br/>
        <table class="slds-table slds-table--bordered slds-table--striped slds-table--cell-buffer slds-table--fixed-layout">
            <thead>
                <tr class="slds-text-heading--label">
                    <th scope="col"><div class="slds-truncate" title="Account Name">Account Name</div></th>
                    <th scope="col"><div class="slds-truncate" title="Phone">Phone</div></th>
                </tr>
            </thead>
            <tbody>
                <aura:iteration items="{!v.mydata}" var="row" indexVar="index">
                    <tr>
                        <th scope="row"><div class="slds-truncate" title="{!row.Name}">{!row.Name}</div></th>
                        <td><div class="slds-truncate" title="{!row.Phone}">{!row.Phone}</div></td>
                    </tr>
                </aura:iteration>
            </tbody>
        </table>
    </div>
</aura:component>

Controller:
({
    doinit : function(component, event, helper) {
        var action = component.get('c.fetchAcc');
        action.setCallback(this, function(response){
            var state = response.getState();
            if(state === "SUCCESS"){
                var allValues = response.getReturnValue();
                console.log("allValues--->>> " + allValues);
                component.set('v.mydata', allValues);
            }
            else if(state === "ERROR") {
                var errors = response.getError();
                if(errors){
                    if(errors[0] && errors[0].message){
                        console.log("Error Message: " + errors[0].message);
                    }
                }
                else{
                    console.log("Unknown Error");
                }
            }
        });
        $A.enqueueAction(action);
    },
    
    newPopup : function(component, event, helper){
        var cmpTarget = component.find('Modalbox1');
        var cmpBack = component.find('Modalbackdrop');
        $A.util.addClass(cmpTarget, 'slds-fade-in-open');
        $A.util.addClass(cmpBack, 'slds-backdrop--open');
    },
    
    saveModal : function(component, event, helper){
        var regForm = component.get("v.accForm");
        var action = component.get("c.saveDetails");
        action.setParams({regForm1  : regForm});
        action.setCallback(this, function(response) {
            var state = response.getState();          
            if (state === "SUCCESS") {
                $A.get('e.force:refreshView').fire();
                var cmpTarget = component.find('Modalbox1');
                var cmpBack = component.find('Modalbackdrop');
                $A.util.removeClass(cmpBack,'slds-backdrop--open');
                $A.util.removeClass(cmpTarget, 'slds-fade-in-open');
                
            }
            else if (state === "ERROR") {
                var errors = response.getError();
                if (errors) {
                    if (errors[0] && errors[0].message) {
                        console.log("Error message: " + 
                                    errors[0].message);
                    }
                } 
                else {
                    console.log(response.getReturnValue());
                }
            }
        });
        $A.enqueueAction(action);
    },
    
    closeNewModal : function(component, event, helper){
        var cmpTarget = component.find('Modalbox1');
        var cmpBack = component.find('Modalbackdrop');
        $A.util.removeClass(cmpBack,'slds-backdrop--open');
        $A.util.removeClass(cmpTarget, 'slds-fade-in-open');
    },
})

CSS:
.THIS {
}

.THIS .slds-section__title{
    background-color: YellowGreen;
    color: white
}
.THIS .slds-modal__header{
    background-color: OliveDrab;
    color: white
}

Apex:
public class PopupFormC {

    @AuraEnabled
    public static List<Account> fetchAcc (){
        return [SELECT Id, Name, Phone FROM Account ORDER BY CreatedDate desc];
    }

	@AuraEnabled
    public static void saveDetails (Account regForm1){ 
    	INSERT regForm1;
    }
}


I hope it helps you.

Kindly let me know if it helps you and close your query by marking it as solved so that it can help others in the future.

Thanks and Regards,
Khan Anas
This was selected as the best answer
KMK91KMK91
Thank you Khan 
Ajay K DubediAjay K Dubedi
Hi,

Below code can fulfill your requirements, Hope this will work for you.

Component :
<aura:component>
    <!--use boolean attribute for Store true/false value,
    make default to "false" so modal box are not display on the load of component. 
    --> 
    <aura:attribute name="isOpen" type="boolean" default="false"/>
    
    <!--Use "slds-m-around_xx-large" class to add standard X-Large padding to the component--> 
    <div class="slds-m-around_xx-large">
        
        <lightning:button variant="brand"
                          label="About"
                          title="About"
                          onclick="{! c.openModel }" />
        <!--Use aura:if tag to display Model Box, on the bese of conditions. [isOpen boolean attribute] -->   
        <aura:if isTrue="{!v.isOpen}">
            
            <!--###### MODAL BOX Start######--> 
            <section role="dialog" tabindex="-1" aria-labelledby="modal-heading-01" aria-modal="true" aria-describedby="modal-content-id-1" class="slds-modal slds-fade-in-open">
                <div class="slds-modal__container">
                    <!-- ###### MODAL BOX HEADER Start ######-->
                    <header class="slds-modal__header">
                        <lightning:buttonIcon iconName="utility:close"
                                              onclick="{! c.closeModel }"
                                              alternativeText="close"
                                              variant="bare-inverse"
                                              class="slds-modal__close"/>
                        <h2 id="modal-heading-01" class="slds-text-heading_medium slds-hyphenate">About</h2>
                    </header>
                    <!--###### MODAL BOX BODY Part Start######-->
                    <div class="slds-modal__content slds-p-around_medium" id="modal-content-id-1">
                        <p><b>The goal of this blog is to provide tips and tricks/workarounds for salesforce developer and admins.
                          
                            cover some of the more basic topics in salesforce.
                            </b>
                        </p>
                    </div>
                    <!--###### MODAL BOX FOOTER Part Start ######-->
                    <footer class="slds-modal__footer">
                        <lightning:button variant="neutral" 
                                          label="Cancel"
                                          title="Cancel"
                                          onclick="{! c.closeModel }"/>
                        <lightning:button variant="brand" 
                                          label="Like and Close"
                                          title="Like and Close"
                                          onclick="{! c.likenClose }"/>
                    </footer>
                </div>
            </section>
            <div class="slds-backdrop slds-backdrop_open"></div>
            <!--###### MODAL BOX Part END Here ######-->
            
        </aura:if>
    </div>
</aura:component>

Controller :
({
   openModel: function(component, event, helper) {
      // for Display Model,set the "isOpen" attribute to "true"
      component.set("v.isOpen", true);
   },
 
   closeModel: function(component, event, helper) {
      // for Hide/Close Model,set the "isOpen" attribute to "Fasle"  
      component.set("v.isOpen", false);
   },
 
   likenClose: function(component, event, helper) {
      // Display alert message on the click on the "Like and Close" button from Model Footer 
      // and set set the "isOpen" attribute to "False for close the model Box.
      alert('thanks for like Us :)');
      component.set("v.isOpen", false);
   },
})
 
Please mark this as best answer if this solves your problem.

Thank you,
Ajay Dubedi