0

Currently, I am using the above code to preselect the first row:

//preselect the first invoice row
setTimeout(() => this.selectedRows = this.invoiceList.map(record=>record.id));

The invoiceList is a list of invoices displayed in my datatable (invoiceList = datatable's data)

By using this code, all the rows of my datatable were going to be preselected, however maxrowselection is 1. So only the first row is preselected. In the browser's console I get this error:

The number of keys in selectedRows for lightning:datatable exceeds the limit defined by maxRowSelection.

I don't know how to access only the first element of my list. Any thoughts?

Thank you!

1 Answer 1

2

The map() method

creates a new array populated with the results of calling a provided function on every element in the calling array.

That's why you're getting that warning in the browser's console.
In order to get only the first element, you can just access it via its index (0):

//preselect the first invoice row
setTimeout(() => this.selectedRows = [this.invoiceList[0].id]);

If you have an instance variable that holds the max row selection value, you can write a function to populate the selectedRows array with at most that number of ids.

fillSelectedRows() {
    const endIndex = Math.min(this.maxRowSelection, this.invoiceList.length);
    const preselectedIds = [];
    for (let i=0; i<endIndex; i++) {
        preselectedIds.push(this.invoiceList[i].id);
    }
    this.selectedRows = preselectedIds;
}

Since slice allows a second parameter greater than the array's length, the same method can be written as

fillSelectedRows() {
    this.selectedRows = this.invoiceList.slice(0, this.maxRowSelection).map(row => row.id);
}
2
  • 1
    For the latter code block, just fillSelectedRows() { this.selectedRows = this.invoiceList.slice(0, this.maxRowSelection).map(row => row.id); } will suffice. Unlike many other languages, JavaScript is smart enough to stop at the end of an array automatically. This also creates a copy, so no need to do so "manually."
    – sfdcfox
    Commented Nov 3, 2021 at 9:15
  • @sfdcfox You're right, I'm going to update the answer, thanks for the tip. Anyway I'd say "slice() is smart enough..."
    – RubenDG
    Commented Nov 3, 2021 at 9:34

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .