• Vaibhav Sharma 166
  • NEWBIE
  • 0 Points
  • Member since 2022

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 0
    Questions
  • 1
    Replies
Hi all,

in the documentation (https://developer.salesforce.com/docs/component-library/bundle/lightning-datatable/documentation) a way is documented to preselect rows programmatically.
For this reason you should use "selected-rows"-attribut on lightning-datatable.

DOCUMENTATION

The selected-rows attribute enables programmatic selection of rows, which is useful when you want to preselect rows.
<lightning-datatable
    columns={columns}
    data={data}
    key-field="id"
    selected-rows={selectedRows}>
</lightning-datatable>
<lightning-button
    label="Select"
    onclick={handleSelect}>
</lightning-button>

To select a row programmatically, pass in the row key-field value.
// Load data via init handler first
// then handle programmatic selection
handleSelect() {
   const rows = ['a'];
   this.selectedRows = rows;
}

My component looks (simplfied) the following way:
export default class MergeDuplicates extends LightningElement {
    @track preSelectedRows = ['0011x00000KOMiJAAX'];
    
    [...]
}

My html-file (simplified) looks the following way:
<lightning-datatable
       key-field="Id"
       data={data}
       columns={columns}
       onrowselection={handleSelected}
       selected-rows={preSelectedRows}
       is-loading={tableLoadingState}>
</lightning-datatable>

My purpose: Preselect the current account, because the lwc is placed on a lightning record page for account.

My problem: Nothing happens. No checkbox is active.

One of my first ideas was the key-field. I changed it from "id" (lowercase) to "Id" (uppercase) but that don't solve the problem.

I don't know any other simpler way to test the preselect of rows for datatable than my example above.

Any suggestions?