I am using standard datatable to display list of records along with checkbox for each record, i want to disable checkbox for few records. How to do using salesforce LWC


While your requirement isn't directly possible with the standard LWC datatable, you could take one of the following alternate approaches. Option 1 would be the easiest alternative and implementing Option 2 is beyond the scope of this answer (you could explore more, if interested).

Option 1:

Using selectedRows attribute and rowselection event handler, clear out the checkbox immediately on a row (if selection is not allowed for the particular row and the end user tries to select it) and display a visual indication to the end user (toast info or data table error). Though this doesn't disable the checkbox at row level, it immediately clears it out and indicates the user not to select it.

Assuming that the datatable would display 5 rows [with row IDs: a, b, c, d, e] and the requirement is to restrict the user from selecting row with ID 'b' (in other words, checkbox on row b should have been disabled), your code should be similar as shown below. Note that you will have to tweak this code for your requirement.

In the HTML file, add the following to the datatable tag: selected-rows={selectedRows} onrowselection={handleRowSelection}

In the JS file, add a new field selectedRows and the following snippet.

handleSelectedRow(event) {
    // Clear the row selection checkbox if it is not allowed. 
    // Note that only the row ID needs to be passed to this array
    this.selectedRows = event.detail.selectedRows.map(row => {
            let rtnId;
            if(row.id !== 'b') // Implement your own code logic instead of this line
                rtnId = row.id;
                    new ShowToastEvent({
                        title: 'Info',
                        message: 'Row selection is not allowed', 
                        variant: 'info'
            return rtnId;
    // Filter out the row that is not allowed for row selection
    event.detail.selectedRows = event.detail.selectedRows.filter(row => row.id !== 'b');
    // In the above filter function implement your own code logic

If you don't want to show toast, you can use the standard data table error attribute to display indication at row level (but this would require that at least one of the columns is marked as editable).

Option 2:

  1. Build a custom datatable (that extends the standard data table) with custom data type (refer to section Creating Custom Data Types here).
  2. This custom data type should implement the checkbox and all the related row selection functionality.
  3. Hide the standard checkbox column using the attribute hide-checkbox-column
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.