Lightning table with multiple checkbox select options and filter table data.

Hi All,

This is good example of Lightning table with multiple checkbox selection and also you can filter the table data.For my convenience i have named the component as DefectTracker.
DefectTracker.cmp
   <aura:component controller="LeadController">
    <aura:handler name="init" action="{!c.doInit}" value="{!this}"/>
    <aura:attribute name="Leads" type="list" />   
    <aura:attribute name="check" type="boolean"/>
    <aura:attribute name="Bools" type="list"/>
    <aura:attribute name="key" type="string"/>
    <!---Use Salesforce Lightning Design System CSS From Static resources-->   
   <ltng:require styles="{!$Resource.salesforcelightningdesignsystem + '/assets/styles/salesforce-lightning-design-system.css'}"/>
   
    <!--declare attributes--> 
   <aura:attribute name="selectedRecord" type="User" default="{}" description="Use,for store SELECTED sObject Record"/>
   <aura:attribute name="listOfSearchRecords" type="User[]" description="Use,for store the list of search records which returns from apex class"/>
   <aura:attribute name="SearchKeyWord" type="string"/>
   <aura:attribute name="Message" type="String" default="Search Result.."/>
    
   <!--declare events hendlers-->  
   <aura:handler name="SelectedUserEvent" event="c:SelectedUserEvent" action="{!c.handleComponentEvent}"/>
   <aura:handler event="aura:waiting" action="{!c.showSpinner}"/>
   <aura:handler event="aura:doneWaiting" action="{!c.hideSpinner}"/>
 
   <!-- https://www.lightningdesignsystem.com/components/lookups/ --> 
   <div class="slds-m-around--large">
   <div aura:id="searchRes" class="slds-form-element slds-lookup slds-is-close" data-select="single">
   <label class="slds-form-element__label" for="lookup-348"> User Name </label><br/>
    <!--This part is for display search bar for lookup-->  
    <div class="slds-form-element__control">            
    <div class="slds-input-has-icon slds-input-has-icon--right">
     <c:svg class="slds-input__icon slds-show" 
         xlinkHref="{!$Resource.salesforcelightningdesignsystem + '/assets/icons/utility-sprite/svg/symbols.svg#search'}" />
     <!-- This markup is for when an record is selected -->
     <div aura:id="lookup-pill" class="slds-pill-container slds-hide">           
      <span class="slds-pill">
       <span class="slds-pill__label">
     {!v.selectedRecord.Name}  
       </span>
       <button class="slds-button slds-button--icon slds-pill__remove" onclick="{!c.clear}">
       <c:svg class="slds-button__icon" xlinkHref="{!$Resource.salesforcelightningdesignsystem + '/assets/icons/utility-sprite/svg/symbols.svg#close'}" />
       <span class="slds-assistive-text">Remove</span>
       </button>
       </span>
       </div>
       <div aura:id="lookupField" class="slds-show">     
       <ui:inputText updateOn="keyup" keyup="{!c.keyPressController}" 
               class="slds-lookup__search-input slds-input " value="{!v.SearchKeyWord}" 
                           aura:id="It" placeholder="Search Users.."/>
        </div> 
        </div>      
        <ui:button class="slds-button slds-button--destructive" 
               press="{!c.FetchSearchValue}">Assign Leads</ui:button>
        </div>
          
         <!--This part is for Display typehead lookup result List-->  
         <div class="slds-lookup__menu slds" id="lookup-348">
            <div class="slds-lookup__item--label slds-text-body--small">{!v.Message}</div>
            <center> <ui:spinner aura:id="spinner"/> </center>
            <ul class="slds-lookup__list" role="listbox">
               <aura:iteration items="{!v.listOfSearchRecords}" var="singleRec">
                  <c:customLookup users="{!singleRec}" />
               </aura:iteration>
            </ul>
         </div>
      </div>
   </div>
    <div class="keyupclass">
    <ui:inputText class="slds-input keyupclass" updateOn="keyup" 
       aura:id="keyupid" keyup="{!c.Keyup}" placeholder="Filter results.." value="{!v.key}"/>
    </div>
    <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.check}" change="{!c.Change}" aura:id="check"/>
    <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="Status">Status</div>
     </th>
      <th scope="col">
      <div class="slds-truncate" title="AssignedTo">AssignedTo</div>
      </th>
      <th scope="col">
      <div class="slds-truncate" title="Company">Company</div>
      </th>
      </tr>
      </thead>
      <tbody>        
      <aura:iteration items="{!v.Leads}" var="lea">
      <tr>
      <th>
      <label class="slds-checkbox">
      <ui:inputCheckbox aura:id="chx" value="" text="{!lea.Id}"/>
      <span class="slds-checkbox--faux" />
      <span class="slds-form-element__label"></span>
      </label>
       </th>
       <th scope="row">
       <div class="slds-truncate" title="{!lea.Name}"><a href="javascript:void(0);">{!lea.Name}</a></div>
       </th>
       <td>
      <div class="slds-truncate" title="{!lea.Status}">{!lea.Status}</div>
       </td>
        <td>
       <div class="slds-truncate" title="{!lea.Assigned_To__r.Name}">{!lea.Assigned_To__r.Name}</div>
        </td>
        <td>
       <div class="slds-truncate" title="{!lea.Company}">{!lea.Company}</div>
       </td>
       </tr>
      </aura:iteration>
       </tbody>
       </table>
    </aura:component>

DefectTrackerController.js

({
doInit : function(component, event, helper) {    
        var action=component.get("c.leadvalues");
        action.setCallback(this,function(result){
            var state=result.getState();
             if (component.isValid() && state === "SUCCESS"){
                 //alert(JSON.stringify(result));
              component.set("v.Leads",result.getReturnValue());   
             }
        });
        
$A.enqueueAction(action);
},
  
keyPressController : function(component, event, helper) {
      // get the search Input keyword   
var getInputkeyWord = component.get("v.SearchKeyWord");
      // check if getInputKeyWord size id more then 0 then open the lookup result List and 
      // call the helper 
      // else close the lookup result List part.   
        if( getInputkeyWord.length > 0 ){
             var forOpen = component.find("searchRes");
               $A.util.addClass(forOpen, 'slds-is-open');
               $A.util.removeClass(forOpen, 'slds-is-close');
            helper.searchHelper(component,event,getInputkeyWord);
        }
        else{  
            component.set("v.listOfSearchRecords", null ); 
             var forclose = component.find("searchRes");
               $A.util.addClass(forclose, 'slds-is-close');
               $A.util.removeClass(forclose, 'slds-is-open');
          }
         
},
  
  // function for clear the Record Selaction 
    clear :function(component,event,heplper){
      
         var pillTarget = component.find("lookup-pill");
         var lookUpTarget = component.find("lookupField"); 
        
         $A.util.addClass(pillTarget, 'slds-hide');
         $A.util.removeClass(pillTarget, 'slds-show');
        
         $A.util.addClass(lookUpTarget, 'slds-show');
         $A.util.removeClass(lookUpTarget, 'slds-hide');
      
         component.set("v.SearchKeyWord",null);
         component.set("v.listOfSearchRecords", null );
    },
    
  // This function call when the end User Select any record from the result list.   
    handleComponentEvent : function(component, event, helper) {
     
    // get the selected Account record from the COMPONETN event  
       var selectedUserGetFromEvent = event.getParam("UserEvent");
  
  component.set("v.selectedRecord" , selectedUserGetFromEvent); 
       
        var forclose = component.find("lookup-pill");
           $A.util.addClass(forclose, 'slds-show');
           $A.util.removeClass(forclose, 'slds-hide');
      
        
        var forclose = component.find("searchRes");
           $A.util.addClass(forclose, 'slds-is-close');
           $A.util.removeClass(forclose, 'slds-is-open');
        
        var lookUpTarget = component.find("lookupField");
            $A.util.addClass(lookUpTarget, 'slds-hide');
            $A.util.removeClass(lookUpTarget, 'slds-show');  
      
},
  // automatically call when the component is done waiting for a response to a server request.  
    hideSpinner : function (component, event, helper) {
        var spinner = component.find('spinner');
        var evt = spinner.get("e.toggle");
        evt.setParams({ isVisible : false });
        evt.fire();    
    },
 // automatically call when the component is waiting for a response to a server request.
    showSpinner : function (component, event, helper) {
        var spinner = component.find('spinner');
        var evt = spinner.get("e.toggle");
        evt.setParams({ isVisible : true });
        evt.fire();    
    },
    Change : function (component, event, helper) {
        var getID=component.get("v.Leads");
        var checkvalue=component.find("check").get("v.value");        
        var chk=component.find("chx"); 
        if(checkvalue==true){
            for(var i=0;i<chk.length;i++){
                chk[i].set("v.value",true);
            }
        }
        else{ 
            for(var i=0;i<chk.length;i++){
                chk[i].set("v.value",false);
            }
        }
        
    
    },
    FetchSearchValue :function (component, event, helper) {
        var chk=component.find("chx");
        var action=component.get("c.updateddata");
        
      var getEnteredValue= component.get("v.selectedRecord");
        var EnteredValue=JSON.stringify(getEnteredValue.Name);
        var Idarr=[];
        if(EnteredValue==null)
            alert('Please select atleast one User');
        for(var i=0;i<chk.length;i++){
            if(chk[i].get("v.value")==true)
            Idarr.push(chk[i].get("v.text"));
        }
        action.setParams({"leadids":Idarr,"assignedto":EnteredValue});
                  action.setCallback(this,function(res){
                     var state=res.getState(); 
                      var returnresult=res.getReturnValue();
                        if(state=='SUCCESS') {   
                           component.set("v.Leads",res.getReturnValue());     
                             }
                             }); 
        
        $A.enqueueAction(action);
    },
    Keyup : function(cmp,event){
        var getkey=cmp.find("keyupid").get("v.value");
        //alert(getkey);
        var action=cmp.get("c.filterdata");
        action.setParams({"key":getkey});
        action.setCallback(this,function(res){
        var state=res.getState(); 
        var returnresult=res.getReturnValue();
        if(state=='SUCCESS') {   
          cmp.set("v.Leads",res.getReturnValue());     
                   }
                  }); 
        $A.enqueueAction(action);
    }
})

DefectTrackerhelper.js

({
searchHelper : function(component,event,getInputkeyWord) {
 // call the apex class method 
     var action = component.get("c.Lookupuser");
      // set param to method  
        action.setParams({
            'Searchkey': getInputkeyWord
          });
      // set a callBack    
        action.setCallback(this, function(response) {
            var state = response.getState();
            if (state === "SUCCESS") {
                var storeResponse = response.getReturnValue();
              // if storeResponse size is equal 0 ,display No Result Found... message on screen.
                if (storeResponse.length == 0) {
                    component.set("v.Message", 'No Result Found...');
                } else {
                    component.set("v.Message", 'Search Result...');
                }
                
                // set searchResult list with return value from server.
                component.set("v.listOfSearchRecords", storeResponse);
            }
 
        });
      // enqueue the Action  
        $A.enqueueAction(action);
    
},
})

 DefectTracker serverside Controller

Public class DefectTrackerController {
    @AuraEnabled
    Public static List<Lead> leadvalues(){        
        List<lead> leadlst=[Select id, name,status,Assigned_to__r.Name,Company from lead order by createddate];
        return leadlst;
    }
        
  @AuraEnabled
    Public static list<User> Lookupuser(String Searchkey){
        String Searchvalue=Searchkey;
        system.debug(Searchkey);
        List<User> SearchUsers=[Select Name from User where name LIKE:'%'+Searchvalue+ '%'];
        return SearchUsers;  
        
    }
     @AuraEnabled
    Public static list<lead> updateddata(list<Id> leadids,String assignedto){
        assignedto=assignedto.replace('"', '');
        system.debug(leadids);
        system.debug(assignedto);
        User userId=[Select id from user where name=:assignedto];
        for(Id lea: leadids){
           lead l=new lead(id=lea,Assigned_To__c=userId.Id);
               update l;
        }
        //leadvalues();
       list<lead> leadlist=[Select name,status,Assigned_to__r.Name,Company from lead order by createddate];
       return leadlist;
    }
     @AuraEnabled
    Public static list<lead> filterdata(String key){
        integer count=0;
        list<lead> leadfilterdata=new List<lead>();
        system.debug(key);
        
       leadfilterdata=  [Select name,status,Assigned_to__r.Name,Company from lead where name LIKE:'%'+key+'%'
                               OR status LIKE:'%'+key+'%' OR Assigned_to__r.Name LIKE:'%'+key+'%' OR Company LIKE:'%'+key+'%' 
                               ];
        return leadfilterdata;
    }
      
    
}

customLookup.cmp
 <aura:component >
    <aura:attribute name="users" type="User" />
   <aura:registerEvent name="SelectedUserEvent" type="c.SelectedUserEvent"/>
     <li role="presentation">
        <span class="slds-lookup__item-action slds-media slds-media--center" id="lookup-option-350" role="option">
         <div class="slds-media__body">
          <div class="slds-input-has-icon slds-input-has-icon--right">
            <c:svg class="slds-input__icon" xlinkHref="{!$Resource.salesforcelightningdesignsystem + '/assets/icons/standard-sprite/svg/symbols.svg#account'}" />                  
            <div class="slds-lookup__result-text"><a onclick="{!c.onSelectChange}">{!v.users.Name}</a></div>
          </div>
        </div>  
        </span>
    </li>
</aura:component>

customLookupController.js
({
onSelectChange :function(component, event, helper) {
      var getSelectUser = component.get("v.users");
    // call the event  
      var compEvent = component.getEvent("SelectedUserEvent");
    // set the Selected Account to the event attribute.
         compEvent.setParams({"UserEvent" : getSelectUser });
    // fire the event
         compEvent.fire();
   
    }
})


Comments

  1. The Controller You have mention is LeadController.Where It is defined ??
    And It not able to found Event name c:SelectedUserEvent .

    ReplyDelete

Post a Comment

Popular posts from this blog

Lightning DataTable Working Example

Wrapper Class Example with multiple delete options