Select multiple records and confirm before delete in Lightning Aura Component

Posted on September 19, 2021 Post Thumbnail

Yo Trailblazers,

In this blog post, I'm going to create a lightning component in which, We display multiple records and select records for delete, Before deleting we confirm and Show toast message of deleted records in Lightning Component.

Image

Check above image for Demo.

I'm going to use Lead Object for above task.

Let's Start :)

First of all we need to create Apex Class for Fetching Leads and Delete Leads.

Check following code for reference.

public class leadsSelectorClass {
    @AuraEnabled
    public static list<Lead> fetchLeads() {
        return [ SELECT Id, Name, Email FROM Lead LIMIT 10];    
    }
    @AuraEnabled
    public static void deleteSelectedleads(list<lead> ldList) {
        delete ldList;
    }
}

It's pretty basic class, No need to explain it.

Let's Create Aura Component

leadsSelector.cmp

<aura:component controller="leadsSelectorClass"  implements="flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId" access="global" >
    <aura:attribute type="Lead[]" name="leadList"/>
    <aura:attribute name="mycolumns" type="List"/>
    <aura:attribute name="selectedLeads" type="List"/>
    <aura:attribute name="isModalOpen" type="boolean" default="false"/>
    <aura:handler name="init" value="{!this}" action="{!c.init}"/>
    <lightning:card title="Delete Selected Leads" iconName="standard:lead">
        
        <lightning:datatable data="{! v.leadList}" 
                             columns="{! v.mycolumns }" 
                             keyField="id"
                             onrowselection="{!c.handleSelect}"/>
        <br/>
        <center>
            <lightning:button onclick="{!c.confirmSelection}" label="Delete Selected Leads" variant="brand"/>
        </center>
        
        <aura:if isTrue="{!v.isModalOpen}">
            
            <!-- Modal/Popup Box starts here-->
            <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/Popup Box Header Starts here-->
                    <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">Confirm Selection</h2>
                    </header>
                    <!--Modal/Popup Box Body Starts here-->
                    <div class="slds-modal__content slds-p-around_medium" id="modal-content-id-1">
                        <p><b>You are going to delete {!v.selectedLeads.length} Leads.
                            </b>
                        </p>
                    </div>
                    <!--Modal/Popup Box Footer Starts here-->
                    <footer class="slds-modal__footer">
                        <lightning:button variant="neutral"
                                          label="Cancel"
                                          title="Cancel"
                                          onclick="{! c.closeModel }"/>
                        <lightning:button variant="brand"
                                          label="Delete Leads"
                                          title="Delete Leads"
                                          onclick="{! c.deleteLeads}"/>
                    </footer>
                </div>
            </section>
            <div class="slds-backdrop slds-backdrop_open"></div>
        </aura:if>
        
    </lightning:card>
    
</aura:component>

leadsSelectorController.js

({
    
    init : function(component, event, helper) {
        
        component.set('v.mycolumns', [
            {label: 'Lead Name', fieldName: 'linkName', type: 'url', 
             typeAttributes: {label: { fieldName: 'Name' }, target: '_blank'}},
            {label: 'Email', fieldName: 'Email', type: 'text'}
        ]);
        
        helper.fetchLeads(component, event);
        
    },
    
    handleSelect : function(component, event, helper) {
        
        var selectedRows = event.getParam('selectedRows'); 
        var setRows = [];
        for ( var i = 0; i < selectedRows.length; i++ ) {
            
            setRows.push(selectedRows[i]);
            
        }
        component.set("v.selectedLeads", setRows);
        
    },
    closeModel: function(component, event, helper) {
        // Set isModalOpen attribute to false  
        component.set("v.isModalOpen", false);
    },
    deleteLeads: function(component, event, helper) {
        var finalRecords = component.get("v.selectedLeads");
        var successMsg = 'Selected ' + finalRecords.length + ' Leads Deleted';
        console.log(successMsg);
        component.set("v.isModalOpen", false);
        var action = component.get("c.deleteSelectedleads");
        action.setParams({ "ldList" : finalRecords });
        action.setCallback(this, function(response) {
            
            var state = response.getState();
            
            if (state === "SUCCESS") {
                var toastEvent = $A.get("e.force:showToast");
                toastEvent.setParams({
                    title : 'Success',
                    message: successMsg,
                    duration:' 5000',
                    key: 'info_alt',
                    type: 'success',
                    mode: 'pester'
                });
                toastEvent.fire();
            }            
            
        });
        
        $A.enqueueAction(action);
        
    },
    confirmSelection : function(component, event, helper) {
        component.set("v.isModalOpen", true);
        var records = component.get("v.selectedLeads");
    }
    
})

leadsSelectorHelper.js

({
    
    fetchLeads : function(component, event) {
        var action = component.get("c.fetchLeads");
        action.setCallback(this, function(response) {
            var state = response.getState();
            if (state === "SUCCESS") {
                var records = response.getReturnValue();
                records.forEach(function(record) {
                    record.linkName = '/' + record.Id;
                    record.CheckBool = false;
                    
                });   
                component.set("v.leadList", records);                
            }            
        });
        $A.enqueueAction(action);
    }
})

After creating this component add it to home page.

img

If you have any question Ask Me

Thanks for Reading :)

Write a comment for suggestions and hit the heart icon.


1301
0

Tags: #lightningComponent #aura

Comments

There are no comments yet.
Your message is required.

Get notified of new posts