August 15, 2018

How to handle selectedRows in lightning:dataTable?

Component:

<aura:component implements="force:appHostable"
    controller="AccountListController">
                
    <aura:attribute type="Account[]" name="acctList"/>
    <aura:attribute name="mycolumns" type="List"/>
    <aura:attribute name="selectedAccts" type="List"/>
    
    <aura:handler name="init" value="{!this}" action="{!c.init}"/>
    
    <div class="slds-box slds-theme_default">
        
        <lightning:datatable data="{! v.acctList }" 
                             columns="{! v.mycolumns }" 
                             keyField="id"
                             onrowselection="{!c.handleSelect}"/>
        <br/>
        <center>
            <lightning:button onclick="{!c.showSelectedName}" label="Show" variant="brand"/>
        </center>
        
    </div>
    
</aura:component>

Controller:

({
    
    init : function(component, event, helper) {
        
        component.set('v.mycolumns', [
            {label: 'Account Name', fieldName: 'linkName', type: 'url', 
            typeAttributes: {label: { fieldName: 'Name' }, target: '_blank'}},
            {label: 'Industry', fieldName: 'Industry', type: 'text'},
            {label: 'Type', fieldName: 'Type', type: 'Text'}
        ]);
        
        helper.fetchAccounts(component, event);
        
    },
    
    handleSelect : function(component, event, helper) {
        
        var selectedRows = event.getParam('selectedRows'); 
        var setRows = [];
        for ( var i = 0; i < selectedRows.length; i++ ) {
            
            setRows.push(selectedRows[i]);

        }
        component.set("v.selectedAccts", setRows);
        
    },
    
    showSelectedName : function(component, event, helper) {
        
        var records = component.get("v.selectedAccts");
        for ( var i = 0; i < records.length; i++ ) {
       
            alert(records[i].Name);
            
        }
    }

})

Helper:

({
    
fetchAccounts : function(component, event) {

        var action = component.get("c.fetchAccts");
        
        action.setCallback(this, function(response) {
            
            var state = response.getState();
            
            if (state === "SUCCESS") {
                
                var records = response.getReturnValue();
                records.forEach(function(record) {
                    
                    record.linkName = '/' + record.Id;
                    record.CheckBool = false;
                    
                });   
                
                component.set("v.acctList", records);
                
            }            
            
        });
        
        $A.enqueueAction(action);
        
}
    
})

Apex Class:

public class AccountListController {
    
    @AuraEnabled
    public static List < Account > fetchAccts() {
        
        return [ SELECT Id, Name, Industry, Type FROM Account LIMIT 5 ];
        
    }
    
}

Output:


11 comments:

  1. This is very helpful...

    ReplyDelete
  2. How I can get the count of selected row and put validation on maximum selection.

    ReplyDelete
    Replies
    1. You have to use length property. For sample code, check https://www.infallibletechie.com/2020/03/how-to-get-count-of-selected-row-in.html

      Delete
  3. I have a similar functionality but to copy the selected rows, create a new record and refresh the list to show the new record as well. Can you please guide me?

    ReplyDelete
    Replies
    1. Pass the selected values to apex class to create a new record and use $A.get('e.force:refreshView').fire() to refresh.

      Delete
  4. I am getting message as undefined

    ReplyDelete
    Replies
    1. Put some console statements to find what is returning and passed.

      Delete
  5. How would keep the previously selected rows while filtering the datatable? IE: currently the selected rows are duplicating the previously selected rows between filters.

    ReplyDelete
    Replies
    1. You have to write that logic inside your filter method.

      Delete