<lightning-datatable> component in Salesforce, users can click checkboxes to select specific rows. But what if you want certain checkboxes to be checked automatically the moment the table loads? To do this, you just need to pass an array of Record IDs to the datatable's selected-rows property.
The lightning-datatable is one of the most heavily used base components in Lightning Web Components (LWC). While rendering data is straightforward, handling default row selection requires a bit of dynamic logic.
In this guide, we will build a custom datatable that fetches data and automatically pre-checks specific rows based on your business criteria.
Step 1: Set Up the Project
First, create a new Lightning Web Component in your Salesforce DX project using the Salesforce CLI.
sf lightning generate component -n dynamicDataTable -d force-app/main/default/lwc
Step 2: Write the JavaScript Controller
Open the dynamicDataTable.js file. For this example, we will wire an Apex method (or use a mock data array) to populate the table. We will also define an array called preSelectedRows which holds the unique IDs of the records that should be checked by default.
import { LightningElement, track } from 'lwc';
export default class DynamicDataTable extends LightningElement {
// Define the columns for the datatable
@track columns = [
{ label: 'Name', fieldName: 'Name' },
{ label: 'Industry', fieldName: 'Industry' },
{ label: 'Status', fieldName: 'Status' }
];
// Mock data (In reality, you would wire an Apex method here)
@track tableData = [
{ Id: '001', Name: 'Acme Corp', Industry: 'Manufacturing', Status: 'Active' },
{ Id: '002', Name: 'Global Tech', Industry: 'Technology', Status: 'Inactive' },
{ Id: '003', Name: 'Salesforce', Industry: 'Software', Status: 'Active' }
];
// Array to hold the IDs of the rows that should be pre-selected
@track preSelectedRows = [];
connectedCallback() {
// Logic to determine which rows should be checked on load.
// Example: Let's automatically select all 'Active' accounts.
const selectedIds = [];
this.tableData.forEach(row => {
if (row.Status === 'Active') {
selectedIds.push(row.Id);
}
});
// Assign the IDs to the bound variable
this.preSelectedRows = selectedIds;
}
// Handles user interaction when they manually check/uncheck boxes
handleRowSelection(event) {
const selectedRecords = event.detail.selectedRows;
console.log('Currently selected records: ', selectedRecords);
}
}
The
selected-rows array must contain values that exactly match the data property defined in the datatable's key-field attribute. If your key-field="Id", your preSelectedRows array must contain IDs (e.g., ['001', '003']), not full objects or names!
Step 3: Create the HTML Markup
Now, open the dynamicDataTable.html file. We will bind our JavaScript arrays directly to the <lightning-datatable> attributes.
<template>
<lightning-card title="Pre-Populated Datatable" icon-name="standard:account">
<div class="slds-m-around_medium">
<lightning-datatable
key-field="Id"
data={tableData}
columns={columns}
selected-rows={preSelectedRows}
onrowselection={handleRowSelection}>
</lightning-datatable>
</div>
</lightning-card>
</template>
data: The array of objects representing your rows.columns: The array of objects defining your column headers and data types.key-field: The unique identifier for each row (usually the record ID).selected-rows: An array of strings representing thekey-fieldvalues of the rows that should be visually checked.
connectedCallback() lifecycle hook or wire adapter to build an array of unique identifiers, and bind that array to the selected-rows attribute in your HTML.
Conclusion
Pre-populating selected records in a Lightning Datatable is a highly requested feature that significantly improves the user experience. By binding an array of record IDs to the selected-rows attribute, you can dynamically highlight important records the second your component renders. You can easily adapt this logic to check boxes based on past user selections, specific status fields, or external API data.
Happy coding!