Here, is a code example of lightning data table with keyfield attribute in it.
<lightning:datatable keyField= "id"
data="{! v.Artifact }"
columns="{! v.columns }"
selectedRows="{! v.selectedRows }"
showRowNumberColumn="true"
onrowselection="{!c.UpdateSelectedRows}"/>
In every example that i found the value of keyField attribute is always id. What is this id?
Also if keyField is used to uniquely identify a row, how to access it's value in onrowselection?I tried the following but nothing worked:
I want to get the row index/row id to uniquely identify each row.UpdateSelectedRows: function(component,event,helper){
let selectedRows = event.getParam('selectedRows');
let setRows = [];
for (let i = 0; i < selectedRows.length; i++){
setRows.push(selectedRows[i].component.get('v.recordId'));
}
console.log('zzzzzzz ',setRows);
//component.set('v.rowsSelected',setRows);
},
Hi Krishnan,I trust you are doing very well.The keyField attribute is required to hold unique row id. It associates each row with a unique identifier. You should always define keyField=”Id”which means row id will be same as record id and it will make easier to update, view and edit records.selectedRows - Enables programmatic row selection with a list of keyField values. To get the row id / record id use the below code:
UpdateSelectedRows : function(component, event, helper) {
var selrows = event.getParam('selectedRows');
var rowsId = [];
for(var i = 0; i<selrows.length; i++){
rowsId.push(selrows[i].Id);
}
console.log('rowsId -> ' + rowsId);
},
You can get the index using below code:
I hope it helps you.Kindly let me inform if it helps you and close your query by marking it as solved so that it can help others in future.UpdateSelectedRows : function(component, event, helper) {
var selrows = event.getParam('selectedRows');
var rows = component.get('v.Artifact');
for(var i = 0; i<selrows.length; i++){
var rowIndex = rows.indexOf(selRows[i]);
console.log('rowIndex---->>> ' + rowIndex);
}
},
Thanks and Regards,
Khan Anas