Checkbox and Radio in Custom Datatable LWC

by Rijwan Mohmmed
0 comment
checkbox-and-radio-in-custom-datatable-lwc-Salesforce-techdicer

Hello friends, today we are going to discuss Checkbox and Radio in Custom Datatable LWC. Sometimes we need a custom data table for our functionality and also need checkbox and radio fields in that table. We can easily implement both fields with the same functionality as the standard LWC Datatable.

Also, check this: Generate Random Number/String in Apex

Key Highlights :

  1. Can select single and multi-select checkboxes.
  2. The radio field selects only one in the same column.
  3. Customize things easily.
  4. Use SLDS Datatable.

Code :

AccountDataController.cls :

public class AccountDataController {
    @AuraEnabled(Cacheable = true)
    public static List<Account> getAccounts(){
      return [SELECT Id, Name, Industry, Type, Phone, Rating, AccountNumber FROM Account ORDER BY Name LIMIT 10];
    }
}

lWCCustomDatatableWithCheckbox.html :

<template>
	<lightning-card variant="Narrow" title="Checkbox and Radio in Custom Datatable LWC" icon-name="standard:account">
		<lightning-button label="Get Selected Records" onclick={getAllSelectedRecord} variant="brand" slot="actions">
		</lightning-button>
		<div class="slds-p-horizontal_small">
			<!-- loader -->
			<div if:true={showSpinner}>
				<lightning-spinner alternative-text="Loading..." variant="brand" class="slds-is-fixed">
				</lightning-spinner>
			</div>
			<!-----/loader------>

			<!-- datatable with checkbox -->
			<div class="tableHeight slds-scrollable_y">
				<table class="slds-table slds-table_cell-buffer slds-table_bordered slds-no-row-hover">
					<thead>
						<tr class="slds-line-height_reset">
							<th class="" scope="col">
								<div class="slds-truncate">
									<lightning-input onchange={handleAllSelected} type="checkbox"
										data-key="allCheckbox">
									</lightning-input>
								</div>
							</th>
							<th class="" scope="col">
								<div class="slds-truncate" title="Name">Name</div>
							</th>
							<th class="" scope="col">
								<div class="slds-truncate" title="Name">Type</div>
							</th>
							<th class="" scope="col">
								<div class="slds-truncate" title="Name">Phone</div>
							</th>
							<th class="" scope="col">
								<div class="slds-truncate" title="Preferred Channel">Single Select Checkbox</div>
							</th>
							<th class="" scope="col">
								<div class="slds-truncate" title="Radio Select">Radio
									Select</div>
							</th>
						</tr>
					</thead>
					<tbody>
						<template for:each={data} for:item="obj">
							<tr key={obj.Id}>
								<th scope="col">
									<div>
										<lightning-input type="checkbox" value={obj.Name} data-id={obj.Id}
											data-key="firstColumnCheckbox" onchange={handleCheckboxSelect}
											name={obj.Id}>
										</lightning-input>
									</div>
								</th>
								<th scope="col">
									<div>{obj.Name}</div>
								</th>
								<th scope="col">
									<div>{obj.Type}</div>
								</th>
								<th scope="col">
									<div>{obj.Phone}</div>
								</th>
								<th scope="col">
									<div>
										<lightning-input type="checkbox" value={obj.Id} name={obj.Id}
											data-check={obj.Id} data-key="singleSelectColumnCheckbox"
											onchange={handleSingleCheckboxSelect}>
										</lightning-input>
									</div>
								</th>
								<th scope="col">
									<div>
										<lightning-input type="radio" value={obj.Id} data-id={obj.Id} name="radio"
											data-name="radio" data-check={obj.Id}>
										</lightning-input>
									</div>
								</th>
							</tr>
						</template>
					</tbody>
				</table>
			</div>
		</div>
	</lightning-card>
</template>

lWCCustomDatatableWithCheckbox.js :

import { LightningElement, wire, track } from 'lwc';
import getAccounts from '@salesforce/apex/AccountDataController.getAccounts';

export default class LWCCustomDatatableWithCheckbox extends LightningElement {
    data = [];
    error;
    @track selectedRecordIds = [];
    @track selectedRadioRecord = '';

    @wire(getAccounts)
    wireAccounts({ error, data }) {
        if (data) {
            this.data = data;
            this.error = undefined;
        } else if (error) {
            this.error = error;
        }
    }

    handleCheckboxSelect(event) {
        let selectedRows = this.template.querySelectorAll('lightning-input[data-key="firstColumnCheckbox"]');
        let allSelected = true;

        selectedRows.forEach(currentItem => {
            if (!currentItem.checked && currentItem.type === 'checkbox') {
                allSelected = false;
            }
        });

        let selectedRow = this.template.querySelector('lightning-input[data-key="allCheckbox"]');

        if (allSelected) {
            selectedRow.checked = true;
        } else {
            selectedRow.checked = false;
        }
    }

    //Select/unselect all rows
    handleAllSelected(event) {
        let selectedRows = this.template.querySelectorAll('lightning-input[data-key="firstColumnCheckbox"]');

        selectedRows.forEach(row => {
            if (row.type == 'checkbox') {
                row.checked = event.target.checked;
            }
        });
    }

    handleSingleCheckboxSelect(event) {
        const boxes = this.template.querySelectorAll('lightning-input[data-key="singleSelectColumnCheckbox"]');
        boxes.forEach(box => box.checked = event.target.name === box.name);
    }

    getAllSelectedRecord() {
        //first column checkbox selected records
        let firstColumnSelectedRecord = [];
        let firstColumnCheckboxRows = this.template.querySelectorAll('lightning-input[data-key="firstColumnCheckbox"]');

        firstColumnCheckboxRows.forEach(row => {
            if (row.type == 'checkbox' && row.checked) {
                firstColumnSelectedRecord.push(row.dataset.id);
            }
        });

        //single selected checkbox record
        let selectedRecord = '';
        let singleColumnCheckbox = this.template.querySelectorAll('lightning-input[data-key="singleSelectColumnCheckbox"]');
        singleColumnCheckbox.forEach(row => {
            if (row.type == 'checkbox' && row.checked) {
                selectedRecord = row.value;
            }
        });

        let selectedRadioRecord = '';
        let selectedRadioRows = this.template.querySelectorAll('lightning-input[data-name="radio"]');

        selectedRadioRows.forEach(currentItem => {
            if (currentItem.type === 'radio' && currentItem.checked) {
                selectedRadioRecord = currentItem.value;
            }
        })

        console.log('multiple selected Record : ' + JSON.stringify(firstColumnSelectedRecord));
        console.log('single checkbox selected Record : ' + selectedRecord);
        console.log('single radio selected Record : ' + selectedRadioRecord);
    }

}

lWCCustomDatatableWithCheckbox.js-meta.xml :

<?xml version="1.0"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
	<apiVersion>55.0</apiVersion>
	<isExposed>true</isExposed>
	<targets>
		<target>lightning__HomePage</target>
	</targets>
</LightningComponentBundle>

Output :

checkbox-and-radio-in-custom-datatable-lwc-output-Salesforce-techdicer
checkbox-and-radio-in-custom-datatable-lwc-output-Salesforce-techdicer

Reference :

  1. SLDS Datatable
What’s your Reaction?
+1
0
+1
0
+1
0
+1
0
+1
1
+1
0

You may also like

Leave a Comment

* By using this form you agree with the storage and handling of your data by this website.