LWC Data Table With Checkbox Example

Written By Venu Gutta Salesforce LWC on Monday, 22 June 2020 | 05:18

LWC  lightning-datatable with checkbox selection

LWC Lightning Data Table With Multiple Records Selection Example

LWC Data Table is the powerful standard slds table provided by salesforce. By using "lightning-datatable" tag we can display set of records in tabular format. If we use Data table in lightning web component we don't need code for table design and function for selecting records explicitly.  Data table respects data type of field value and displays in respective format.

Important Attributes for Data Table in Lightning Web component:

Key-field: Unique identifier for each record in a Lwc table and It is used to identify predefined selected records when page loads.

Columns: Which is used to store set of field properties like label, type, fieldName(api name of the field).

data: List of records data which are used to display on table.

hide-checkbox-column: By default LWC Data table displays checkbox, if we want to hide we need to add "hide-checkbox-column" in the data table tag.

Usage of getSeletdRows() in Lightning Web Component Data Table:

By using getSelectdRows function we can easily get checkbox selected records on the table.

Example LWC Data Table: Displaying list of opportunities in Data table in web component and delete selected records.

Apex controller class for Lightning web component Data table

public with sharing class OpportunityController {
    public static List<opportunity>  fetchOpportunityList(){
        return [SELECT Id, Name, StageName,Amount From Opportunity LIMIT 5];
    public static void deleteOpportunities(List<opportunity> oppList){
        delete oppList;

import { LightningElement,wire,track } from 'lwc';
import {refreshApex} from '@salesforce/apex';
import getAllOps from '@salesforce/apex/OpportunityController.fetchOpportunityList';
import deleteOpportunities from '@salesforce/apex/OpportunityController.deleteOpportunities';
const COLS=[
    {label:'Name',fieldName:'Name', type:'text'},
    {label:'Stage',fieldName:'StageName', type:'text'},
    {label:'Amount',fieldName:'Amount', type:'currency'}
export default class DataTableInLwc extends LightningElement {
    @wire(getAllOps) oppList;
        var selectedRecords =
        deleteOpportunities({oppList: selectedRecords})
            return refreshApex(this.oppList);
            alert('Cloud not delete'+JSON.stringify(error));

    <lightning-card title="Opportunity">
        <lightning-button slot="actions" label="Delete" onclick={deleteRecord}></lightning-button>
        <div class="slds-box">
            data={oppList.data} columns={cols} key-field="Id">

Output of Lwc Data table with select checkbox


Post a comment