• 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.
    syntax:
    this.template.querySelector("lightning-datatable").getSelectedRows();

    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

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


    dataTableInLwc.js
     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 {  
       cols=COLS;  
       @wire(getAllOps) oppList;  
       deleteRecord(){  
         var selectedRecords =  
          this.template.querySelector("lightning-datatable").getSelectedRows();  
         deleteOpportunities({oppList: selectedRecords})  
         .then(result=>{  
           return refreshApex(this.oppList);  
         })  
         .catch(error=>{  
           alert('Cloud not delete'+JSON.stringify(error));  
         })  
       }  
     }  
    

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

    Output of Lwc Data table with select checkbox



  • 4 comments to ''LWC Data Table With Checkbox Example"

    ADD COMMENT
    1. Hi Admin,
      IS it possible to stop end user to select only one row in a pagination. If yes, could you please share the code. I used max-row-selection but need the checkbox to the end user.

      -
      Thanks,
      Zakeer.

      ReplyDelete
      Replies
      1. it is difficult to achieve checkbox functionality along with pagination in data table. You can try custom table where you can show checkbox column. Once user selects one of the record then you need to clear the previously selected value.

        Delete
    2. while use wrapper class it not work
      below i attach the code

      lwc html



      lwc -js

      update(){
      alert("1");
      if(this.selectRecordName == ''){
      alert('Select Owner Name');
      }
      var selectedRecords = this.template.querySelector('lightning-datatable').getSelectedRows();
      alert(selectedRecords);
      updateOwner({ ownerId : this.selectRecordId,lstAccount : selectedRecords })
      .then(result => {
      const toastEvent = new ShowToastEvent({
      title: "Owner Updated",
      message: "AccountOwner Sucessfully Updated",
      variant: "success"
      });
      this.dispatchEvent(toastEvent);
      return refreshApex(this.lstAccount);
      });
      }

      apex

      @AuraEnabled(cacheable=true)
      public static void updateOwner(string ownerId,List lstAccount){
      system.debug(lstAccount);
      List lstAccounts = new List() ;
      for(AccountWrapper acc:lstAccount){
      Account newAccount = new Account(Id=acc.Id,ParentId=ownerId);
      lstAccounts.add(newAccount);
      }
      system.debug(lstAccounts);
      update lstAccounts;
      }

      is there need any files are import for getSelectedRows();

      ReplyDelete
      Replies
      1. What's happening currently. What you are getting in "alert(selectedRecords)"

        Delete