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.
Also, check this: JSON Generator Apex Salesforce
Key Highlights :
- Can fetch selected record rows
- Use getSelectedRows() for selected rows in Lightning Datatable.
- Create a button to get selected records.
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 :
