Skip to content

Instantly share code, notes, and snippets.

@dhaniksahni
Created August 16, 2020 19:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dhaniksahni/23643d0cd35409ace8963acf14fe9679 to your computer and use it in GitHub Desktop.
Save dhaniksahni/23643d0cd35409ace8963acf14fe9679 to your computer and use it in GitHub Desktop.
Single Row Selection in LWC
import { LightningElement, wire } from 'lwc';
import getContactList from '@salesforce/apex/ContactController.getContactList';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
const columns = [
{ label: 'First Name', fieldName: 'FirstName' },
{ label: 'Last Name', fieldName: 'LastName' },
{ label: 'Title', fieldName: 'Title' },
{ label: 'Phone', fieldName: 'Phone', type: 'phone' },
{ label: 'Email', fieldName: 'Email', type: 'email' }
];
export default class SingleSelectDatatable extends LightningElement {
error;
columns = columns;
contact=[];
connectedCallback()
{
getContactList()
.then((result,error) => {
if (result) {
this.contact=result;
} else if (error) {
console.error(error);
}
})
}
handleRowSelection = event => {
var selectedRows=event.detail.selectedRows;
if(selectedRows.length>1)
{
var el = this.template.querySelector('lightning-datatable');
selectedRows=el.selectedRows=el.selectedRows.slice(1);
this.showNotification();
event.preventDefault();
return;
}
}
showNotification() {
const event = new ShowToastEvent({
title: 'Error',
message: 'Only one row can be selected',
variant: 'warning',
mode: 'pester'
});
this.dispatchEvent(event);
}
}
@shihabus
Copy link

you don't have to do this. Just set max-row-selection attribute on the table to 1

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment