function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Shubham Sinha 33Shubham Sinha 33 

Checkbox in lightning datatable

I created a lightning component where i have used 4 buttons.My component also consits one datatable with checkbox.Now, I need to implement if checkbox is checked from the datatable then action should perform from the lightning button.

Please help me on this.
Best Answer chosen by Shubham Sinha 33
Khan AnasKhan Anas (Salesforce Developers) 
Hi Shubham,

Greetings to you!

Below is the sample code to delete records from lightning:datatable using the checkbox and button. Kindly modify the code as per your requirement.

Apex:
public class DatatableCheckboxC {
    
    @AuraEnabled
    public static List<Account> fetch(){
        List<Account> acc = [SELECT Name, Phone, Rating FROM Account LIMIT 20];
        return acc;
    }
    
    @AuraEnabled
    public static void deleteForm(List<Account> lstId) {
        List<Account> rf = [SELECT Id FROM Account WHERE Id IN :lstId];
        delete rf;
    }
}

Component:
<aura:component controller="DatatableCheckboxC"
                implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction" 
                access="global" >
    
    <aura:attribute name="PageHeading" type="String" default="Delete Records"/>
    <aura:attribute name="mydata" type="Object"/>
    <aura:attribute name="mycolumns" type="List"/>
    <aura:attribute name="delIds" type="List"/>
    
    <aura:handler name="init" value="{!this}" action="{!c.init}" />
    <aura:handler event="force:refreshView" action="{!c.init}" />
    
    <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/>
    
    <div class="slds-grid slds-grid--align-end"> 
        <lightning:button variant="brand" label="Delete" onclick="{!c.doDelete}"/>
    </div>
    <lightning:datatable data="{! v.mydata }" 
                         columns="{! v.mycolumns }" 
                         keyField="Id" 
                         onrowselection="{! c.handleRowAction }"/>
</aura:component>

Controller:
({
    init : function(component, event, helper) {
        component.set('v.mycolumns', [
            {label: 'Account Name', fieldName: 'Name', type: 'text'},
            {label: 'Phone', fieldName: 'Phone', type: 'phone'},
            {label: 'Rating', fieldName: 'Rating', type: 'text'}
        ]);
        
        var action = component.get("c.fetch");
        action.setCallback(this, function(response) {
            var state = response.getState();
            if (state === "SUCCESS") {
                console.log(response.getReturnValue());
                component.set("v.mydata", response.getReturnValue());
            }
            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);
    },
    
    handleRowAction : function(component, event, helper){
        var selRows = event.getParam('selectedRows');
        component.set("v.delIds",selRows);
    },
    
    doDelete : function(component, event, helper){
        var delIdList = component.get("v.delIds");
        var action = component.get('c.deleteForm');
        action.setParams({lstId : delIdList});
        action.setCallback(this, function(response) {
            var state = response.getState();
            if (state === "SUCCESS") {
                $A.get('e.force:refreshView').fire();
                alert('Successfully Deleted');   
            }
            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);
    },
})

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. It will help to keep this community clean.

Thanks and Regards,
Khan Anas

All Answers

Khan AnasKhan Anas (Salesforce Developers) 
Hi Shubham,

Greetings to you!

Below is the sample code to delete records from lightning:datatable using the checkbox and button. Kindly modify the code as per your requirement.

Apex:
public class DatatableCheckboxC {
    
    @AuraEnabled
    public static List<Account> fetch(){
        List<Account> acc = [SELECT Name, Phone, Rating FROM Account LIMIT 20];
        return acc;
    }
    
    @AuraEnabled
    public static void deleteForm(List<Account> lstId) {
        List<Account> rf = [SELECT Id FROM Account WHERE Id IN :lstId];
        delete rf;
    }
}

Component:
<aura:component controller="DatatableCheckboxC"
                implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction" 
                access="global" >
    
    <aura:attribute name="PageHeading" type="String" default="Delete Records"/>
    <aura:attribute name="mydata" type="Object"/>
    <aura:attribute name="mycolumns" type="List"/>
    <aura:attribute name="delIds" type="List"/>
    
    <aura:handler name="init" value="{!this}" action="{!c.init}" />
    <aura:handler event="force:refreshView" action="{!c.init}" />
    
    <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/>
    
    <div class="slds-grid slds-grid--align-end"> 
        <lightning:button variant="brand" label="Delete" onclick="{!c.doDelete}"/>
    </div>
    <lightning:datatable data="{! v.mydata }" 
                         columns="{! v.mycolumns }" 
                         keyField="Id" 
                         onrowselection="{! c.handleRowAction }"/>
</aura:component>

Controller:
({
    init : function(component, event, helper) {
        component.set('v.mycolumns', [
            {label: 'Account Name', fieldName: 'Name', type: 'text'},
            {label: 'Phone', fieldName: 'Phone', type: 'phone'},
            {label: 'Rating', fieldName: 'Rating', type: 'text'}
        ]);
        
        var action = component.get("c.fetch");
        action.setCallback(this, function(response) {
            var state = response.getState();
            if (state === "SUCCESS") {
                console.log(response.getReturnValue());
                component.set("v.mydata", response.getReturnValue());
            }
            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);
    },
    
    handleRowAction : function(component, event, helper){
        var selRows = event.getParam('selectedRows');
        component.set("v.delIds",selRows);
    },
    
    doDelete : function(component, event, helper){
        var delIdList = component.get("v.delIds");
        var action = component.get('c.deleteForm');
        action.setParams({lstId : delIdList});
        action.setCallback(this, function(response) {
            var state = response.getState();
            if (state === "SUCCESS") {
                $A.get('e.force:refreshView').fire();
                alert('Successfully Deleted');   
            }
            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);
    },
})

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. It will help to keep this community clean.

Thanks and Regards,
Khan Anas
This was selected as the best answer
Nida Khan 5Nida Khan 5
Thanks @khan Anas