You need to sign in to do that
Don't have an account?
sfdc developer 1056
how to get the Key-Field id or row index in javascript LWC
Hi Team,
I'm building the lightning data table where I'm using "id" as a key-field
Thank you in advance
I'm building the lightning data table where I'm using "id" as a key-field
<lightning-datatable key-field="id" data={accountList} columns={columns} onrowselection={handleRowSelected} selected-rows={selection} oncellchange={handleCellChange}> </lightning-datatable>I want to retrive the row id in my javascript. How to fetch that ? I have tried many solution like:
let selectedRecords = this.template.querySelector("lightningdatatable").getSelectedRows(); if (selectedRecords) { for (const key in selectedRecords) { console.log('checking',selectedRecords[key].event.currentTarget.dataset.id); console.log('checking',selectedRecords[key]['id']); console.log('checking',selectedRecords[key].event.target.dataset.rowId); console.log('checking',selectedRecords[key].dataset.id); console.log('checking',selectedRecords[key]['id']); }Please let me know if anybody knows the solutions.
Thank you in advance
Try Below Code Please Mark It As Best Answer If It Helps
Thank You!
Thanks for reply. But it is not working and giving error saying ReferenceError: key is not defined in lWC.
Also i dnt want Id(record Id), I want the row id/ Key field value.
Try this code : ---------------
If you find your Solution then mark this as the best answer to close this question.
Thank you!
Regards,
Suraj Tripathi
Inorder to fetch the record id of the current selected row in lightning data table we can use the below workaround.
HTML
<lightning-datatable class="slds-p-left_x-small" hide-checkbox-column={hidecheckboxcolumn}
key-field="id" data={activeGridData} columns={columns} onrowaction={handleRowAction}
onheaderaction={handleHeaderAction} onrowselection={getSelectedName}>
</lightning-datatable>
Javascript
getSelectedName(event){
//event.detail.selectedrows will fetch all the selected records. Since we need the latest clicked record we need to fetch the last selected row
let lastidx = event.detail.selectedrows.length - 1;
let selectedrow = event.detail.selectedrows[lastidx];
}