function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
venkat bojjavenkat bojja 

DataTable in lightning

Hi Team,

I have a one data table with check boxes. Ineed to check only one check box at a time with the checked record ID.Please help me on this.
                                     Thanks in advance...

Reference code:

Component:

<aura:component  controller="ContactAuraController" implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction" access="global" >

    <!--Declare Event Handlers--> 
    <aura:handler name="init" action="{!c.doInit}" value="{!this}"/>
     
    <!--Declare Attributes-->
    <aura:attribute name="contactList" type="list" />   
    <aura:attribute name="isSelectAll" type="boolean" default="false"/>
      <aura:attribute name="recdId" type="String" /> 
    <div class="slds-m-around_xx-large">
        <h1 class="slds-text-heading--medium">Contacts</h1>
        <br/>
        <!--Contact List Table-->
        <table class="slds-table slds-table--bordered slds-table--cell-buffer" role="grid">      
            <thead>  
                <tr class="slds-text-title--caps">
                    <th>           
                        <label class="slds-checkbox">
                            <ui:inputCheckbox value="{!v.isSelectAll}" change="{!c.handleSelectedContacts}" aura:id="selectAll"/>
                            <span class="slds-checkbox--faux" />
                            <span class="slds-form-element__label"></span>
                        </label>
                    </th>
                    <th scope="col">
                        <div class="slds-truncate" title="Name">Name</div>
                    </th>
                    <th scope="col">
                        <div class="slds-truncate" title="Account">Account</div>
                    </th>
                     
                    <th scope="col">
                        <div class="slds-truncate" title="Phone">Phone</div>
                    </th>
                     
                    <th scope="col">
                        <div class="slds-truncate" title="Email">Email</div>
                    </th>
                </tr>
            </thead>
            <tbody>        
                <aura:iteration items="{!v.contactList}" var="con">
                    <tr>
                        <th>
                            <label class="slds-checkbox">
                                <ui:inputCheckbox aura:id="checkContact" value="" text="{!con.Id}"/>
                                <span class="slds-checkbox--faux" />
                                <span class="slds-form-element__label"></span>
                            </label>
                        </th>
                        <th scope="row">
                            <div class="slds-truncate" title="{!con.Name}">{!con.Name}</div>
                        </th>
                        <td>
                            <div class="slds-truncate" title="{!con.Account.Name}">{!con.Account.Name}</div>
                        </td>
                        <th scope="row">
                            <div class="slds-truncate" title="{!con.Phone}">{!con.Phone}</div>
                        </th>
                        <td>
                            <div class="slds-truncate" title="{!con.Email}">{!con.Email}</div>
                        </td>
                    </tr>
                </aura:iteration>
            </tbody>
        </table>
        <div>
            <br/>
            <!-- <lightning:button label="Submit" class="slds-button_brand" onclick="{!c.handleSelectedContacts }"  /> -->
        </div>
    </div>
</aura:component>

==================================
Controller.JS

({
    //get Contact List from apex controller
    doInit : function(component, event, helper) {
        var action = component.get("c.getContactList");
        action.setParams({
        });
        action.setCallback(this, function(result){
            var state = result.getState();
            if (component.isValid() && state === "SUCCESS"){
                component.set("v.contactList",result.getReturnValue());   
            }
        });
        $A.enqueueAction(action);
    },
     
    //Select all contacts
    
     
    //Process the selected contacts
    
    
    
    getSelectedName: function (cmp, event,helper) {
        debugger; 
        var selectedRows = event.getParam('selectedRows'); 
        
      
        for (var i = 0; i < selectedRows.length; i++){
           // alert(selectedRows[i].Id);
            cmp.set('v.recdId', selectedRows[i].Id); 
            
            var RecordID = cmp.get("v.recdId");
            alert('RecordID'+RecordID);
        
        }
    },
})
=================================
Apex Controller

public class ContactAuraController {
 @AuraEnabled
    Public static List<Contact> getContactList(){
        //get all contact list
        List<Contact> conList = [SELECT Id, Name, Account.Name, Phone, Email FROM Contact LIMIT 10];
        return conList;
    }
}

=====================================
Reference Image:

User-added image
Best Answer chosen by venkat bojja
Anil SomasundaranAnil Somasundaran
Hi Venkat,

I have modified the JS Controller method for enabling the checking and unchecking functionality on the selected checkbox.
onCheckboxChange : function (component,event,helper){
        //debugger; 
        var checkboxes = component.find('checkContact');
        var value =false;
        if (!Array.isArray(checkboxes)) {
            checkboxes.set('v.value', value);
        } else {
            checkboxes.forEach(function(cb) {
                cb.set('v.value', value);
            });
        }
        var contactId = event.getSource().get("v.text");
        var prevRecordId = component.get("v.recdId");
        
        if (contactId == prevRecordId) {
            event.getSource().set("v.value",false);
            component.set("v.recdId","");
        }else {
            event.getSource().set("v.value",true);
            //text attribute of the checbox contains the value of contact Id
            
            console.log("ContactId"+contactId);
            //sets the value to recordId attribute defined in the component view part
            component.set("v.recdId",contactId);
            console.log("record Id", component.get("v.recdId"));
        }
        
    }
Thanks,
Anil
Please mark this as best answer and upvote if your query has been resolved. Visit my blog to find more about lightning https://techevangel.com/author/anilsomasundaran/  (http://techevangel.com/author/anilsomasundaran/)
 

All Answers

Ashwin Kumar SrinivasanAshwin Kumar Srinivasan
Hi 

I don't think there is an attribute to do this yet I might be wrong, but you can hide the select all checkbox via css 
 
.THIS.datatableCheckboxHide .slds-th__action > .slds-checkbox{
    display:none;
}
if the lightning:datatable is direct child to your component you can pass
class="datatableCheckboxHide"
If you wanna hide all checkbox underneath the action you can do 
 
.THIS .slds-th__action > .slds-checkbox{
    display:none;
}
dandamudidandamudi
@venkat
you can not hide the All check box only , but you can hide the entire colum 
if you want to keep row level check box?  and
you want only one check box at a time? and
if check 2nd one after already checked 1st one ?
all aboe condition you can acheive by rowaction like this
onrowselection="{! c.getSelectedName }" 
in controller.js you can add logic by using length data

at the same time you want control the check all button by using hadle header actions
init: function (cmp, event, helper) { 
var headerActions = [ 
             {
                label: 'All', 
               checked: true, 
                name:'all'
              } 
       ];
  cmp.set('v.mycolumns', [
            // other column data
            {
                label: 'Publishing State',
                fieldName: 'published',
                type: 'text',
                actions: headerActions
            }
        ]);
},

handleHeaderAction: function (cmp, event, helper) {
        // Retrieves the name of the selected filter
        var actionName = event.getParam('action').name;
        // Retrieves the current column definition
        // based on the selected filter
        var colDef = event.getParam('columnDefinition');
        var columns = cmp.get('v.mycolumns');
        var activeFilter = cmp.get('v.activeFilter');
     
    }

please click upvote button if this answer helps for issue.
Anil SomasundaranAnil Somasundaran
@venkat bojja

It is possible to modify your component with only single checkbox selection at a time.
var checkboxes = component.find('checkContact');
        var value =false;
        if (!Array.isArray(checkboxes)) {
            checkboxes.set('v.value', value);
        } else {
            checkboxes.forEach(function(cb) {
                cb.set('v.value', value);
            });
        }
        event.getSource().set("v.value",true);


The modified code is available at this link (https://gist.github.com/anilsomasundaran/14132bb8ee0a0c9932d5ddf1d8bb7bc1)
or
Go to my blog https://techevangel.com/2018/04/14/lightning-datatable-with-single-checkbox-selection/

Please mark this as best answer and upvote if your query has been resolved. Visit my blog to find more about lightning https://techevangel.com/author/anilsomasundaran/ 
venkat bojjavenkat bojja
Hi ANil,
            Thanks alot for your help. This code is helped me almost 90%. But i need to get the record Id when the check box is checked. I tried alot please help me on this....
                                          Thanks in advance...
Reference Code:

<aura:attribute name="recdId" type="String" /> 

 <th>
                            <label class="slds-checkbox" id = "{!con.Id}" >
                                <ui:inputCheckbox aura:id="checkContact" name="{!con.Id}" text="{!con.Id}" change="{!c.onCheckboxChange}" /> 
                               <!-- <lightning:input aura:id="checkContact" type="checkbox" label=" " name="{!con.Id}" checked="false" onchange="{!c.onCheckboxChange}"/> -->
                                <span class="slds-checkbox--faux" />
                                <span class="slds-form-element__label"></span>
                            </label>
                        </th>

============================================
Controller.JS

  onCheckboxChange : function (component,event,helper){
        //debugger; 
        console.log(component.find('checkContact'));
        var RecordID = component.get("v.recdId");
        var checkboxes = component.find('checkContact');
        var value =false;
        if (!Array.isArray(checkboxes)) {
            checkboxes.set('v.value', value);
            alert(checkboxes.name);
            component.set('v.recdId', checkboxes.name);
        } else {
            checkboxes.forEach(function(cb) {
                cb.set('v.value', value);
            });
          var RecordID = component.get("v.recdId");
          alert('RecordID'+RecordID);
        }
        
        event.getSource().set("v.value",true);
      
        
    },
Thanks
​Venkat
 
Anil SomasundaranAnil Somasundaran
Hi Venkat,

Do you need to assign the selected row id (contact id ) into the recordId attribute, right?

In the component, the checkbox element should look like this
<ui:inputCheckbox aura:id="checkContact" name="test" value="" text="{!con.Id}" change="{!c.onCheckboxChange}"/>

In the JS controller, I fetched the text attribute of the checkbox element.
onCheckboxChange : function (component,event,helper){
        //debugger; 
        var checkboxes = component.find('checkContact');
        var value =false;
        if (!Array.isArray(checkboxes)) {
            checkboxes.set('v.value', value);
        } else {
            checkboxes.forEach(function(cb) {
                cb.set('v.value', value);
            });
        }
        event.getSource().set("v.value",true);
        //text attribute of the checbox contains the value of contact Id
        var contactId = event.getSource().get("v.text");
        //sets the value to recordId attribute defined in the component view part
        component.set("v.recdId",contactId);
    }

I have mapped selected record's contact Id to 'recdId' attribute that you defined in the component. Please let me know if it works

Thanks,
Anil

Please mark this as best answer and upvote if your query has been resolved. Visit my blog to find more about lightning https://techevangel.com/author/anilsomasundaran/ 
venkat bojjavenkat bojja
Hi Anil Somasundaran,
                                     When my dataTable is having only  one record in that scenario i am trying to to check that check box but getting Error message like  checkboxes.forEach is not a function.How can we resolve this issue.Please help me on this....
                                                Thanks in advance....

Thanks 
Venkat
Anil SomasundaranAnil Somasundaran
Hi Venkat,
It was working fine if the table has only one record. I have included all the modified code in the below link. please check
https://gist.github.com/anilsomasundaran/14132bb8ee0a0c9932d5ddf1d8bb7bc1

Thanks,
Anil
Please mark this as best answer and upvote if your query has been resolved. Visit my blog to find more about lightning https://techevangel.com/author/anilsomasundaran/  (http://lightning https://techevangel.com/author/anilsomasundaran/ )
venkat bojjavenkat bojja
Hi Anil Somasundaran, 
I am having another problem could you please try to give me the solotution.
When i am clicking on that  check i got checked and  if i clicked on that same check box it should uncheck but it is not happening.
Please help me on this...Thanks in advanced...

Thanks
Venkat
 
Anil SomasundaranAnil Somasundaran
Hi Venkat,

I have modified the JS Controller method for enabling the checking and unchecking functionality on the selected checkbox.
onCheckboxChange : function (component,event,helper){
        //debugger; 
        var checkboxes = component.find('checkContact');
        var value =false;
        if (!Array.isArray(checkboxes)) {
            checkboxes.set('v.value', value);
        } else {
            checkboxes.forEach(function(cb) {
                cb.set('v.value', value);
            });
        }
        var contactId = event.getSource().get("v.text");
        var prevRecordId = component.get("v.recdId");
        
        if (contactId == prevRecordId) {
            event.getSource().set("v.value",false);
            component.set("v.recdId","");
        }else {
            event.getSource().set("v.value",true);
            //text attribute of the checbox contains the value of contact Id
            
            console.log("ContactId"+contactId);
            //sets the value to recordId attribute defined in the component view part
            component.set("v.recdId",contactId);
            console.log("record Id", component.get("v.recdId"));
        }
        
    }
Thanks,
Anil
Please mark this as best answer and upvote if your query has been resolved. Visit my blog to find more about lightning https://techevangel.com/author/anilsomasundaran/  (http://techevangel.com/author/anilsomasundaran/)
 
This was selected as the best answer
venkat bojjavenkat bojja
Hi Anil Somasundaran,

It is working fine. I am very thankful to you. 

Thanks
Venkat