Get Selected Rows In Lightning Datatable In LWC

by Rijwan Mohmmed
get-selected-rows-in-lightning-datatable-in-lwc-techdicer

Hello friends, today we are going to discuss how to Get Selected Rows In Lightning Datatable In LWC. We use getSelectedRows() to get the selected rows of the lightning Datatable. Lightning Datatable is a powerful tool, and now, you can leverage LWC to effortlessly capture selected rows’ data and perform actions accordingly.

Also, check this: JSON Generator Apex Salesforce

Key Highlights :

  1. Can fetch selected record rows
  2. Use getSelectedRows() for selected rows in Lightning Datatable.
  3. Create a button to get selected records.
  4. User-Centric: Empower users to efficiently interact with data by allowing them to select multiple rows for action.
  5. Contextual Processing: Use selected data to trigger workflows, updates, or any operations that align with your business logic.
  6. Enhanced Efficiency: Simplify data manipulation by selecting and processing rows directly within the table.

🚀 Elevate Your LWC Expertise: By mastering the art of fetching selected rows in Datatable, you’re enriching your data-driven solutions. Whether it’s mass updates, lead conversions, or any operation requiring row-based actions, this technique enhances your LWC toolkit.

Code :

Step 1: Here we will create an Apex Class for fetching account records. Create an Auraenabled static method that is invoked from the LWC component.

DataController.cls :

public with sharing class DataController {
    @AuraEnabled (cacheable=true)
    public static List<Account> retrieveAccounts(){
        return [SELECT Id, Name, Type, BillingCountry
                FROM Account
                LIMIT 2000];
    }
}

Step 2: in this step, We will create an LWC component in which we create Lightning Datatable with checkboxes.

SelectedRowsLWC.Html :

<template>
    <lightning-Card title="Account List" icon-name="standard:account">
        <lightning-button   variant="Neutral" 
                            label="Selected Records"
                            title="Selected Records"
                            onclick={getSelectedRec} 
                            slot="actions"
                            icon-name="utility:check">
        </lightning-button>
        <div style="border-top: 1px solid rgb(221 219 218);">
            <!-- datatable -->
            <lightning-datatable
                    key-field="id"
                    data={data}
                    columns={columns}
                    column-widths-mode="fixed">
            </lightning-datatable>
            <!-- /datatable -->
        </div>
    </lightning-Card>
</template>

SelectedRowsLWC.Js :

import { LightningElement, track, wire } from 'lwc';
import retrieveAccounts from '@salesforce/apex/DataController.retrieveAccounts';
const columns = [
    { label: 'Name', fieldName: 'Name' },
    { label: 'Type', fieldName: 'Type' },
    { label: 'BillingCountry', fieldName: 'BillingCountry'},       
];

export default class SelectedRowsLWC extends LightningElement {
    @track data;
    @track columns = columns;
    @track error;

    @wire(retrieveAccounts)
    wiredAccounts({ error, data }) {
        if (data) {
            this.data = data;
            this.error = undefined;
        } else if (error) {
            this.error = error;
            this.data = undefined;
        }
    }

    getSelectedRec() {
      var selectedRecords =  this.template.querySelector("lightning-datatable").getSelectedRows();
      if(selectedRecords.length > 0){
          console.log('selectedRecords are ', selectedRecords);

          let ids = '';
          selectedRecords.forEach(currentItem => {
              ids = ids + ',' + currentItem.Id;
          });
          this.selectedIds = ids.replace(/^,/, '');
          this.lstSelectedRecords = selectedRecords;
          alert(this.selectedIds);
      }   
    }
}

OutPut :

get-selected-rows-in-lightning-datatable-in-lwc-output-techdicer
get-selectedrows-in-lightning-datatable-in-lwc-output-techdicer

Reference :

  1. LWC Lightning Datatable
What’s your Reaction?
+1
19
+1
3
+1
3
+1
3
+1
2
+1
7

You may also like

Leave a Comment