Create Lightning datatable with sorting of columns Salesforce

by Himanshu Goyal
0 comment
How-to-create-Lightning-datatable-with-sorting-of-columns

Hello, Friends today we will learn Create Lightning datatable with sorting of columns Salesforce. In this blog, we create sortable lightning datatable. We use the datatable attribute for sorting columns.

  <lightning:datatable 
        data="{!v.Caselist}"
        columns="{!v.mycolumns }"
        keyField="id" 
        hideCheckboxColumn="true"
        showRowNumberColumn="true"
        sortedBy="{!v.sortBy}"
        sortedDirection="{!v.sortDirection}"
        onsort="{!c.handleSort}"
   />
  1. sortedBy : we give sortable column name here , like if you want sort by price field then give this value price.
  2. sortedDirection : Order of records ex. ASC and DESC.
  3. onsort : whenever we click the header of table column it will call the sorting method like in our case we gave handleSort in this method sorting logic implement.

Lightning datatable with sorting

sortingTable.comp :

<aura:component implements="flexipage:availableForAllPageTypes"
                access="global"
                controller="ControllerForCaseList">
	
    <aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
    
    
    
    <aura:attribute name="Caselist" type="Case[]"/>
    <aura:attribute name="mycolumns" type="List"/>
    <aura:attribute name="sortBy" type="String"/>
    <aura:attribute name="sortDirection" type="String"/>
           
    
       
  <lightning:datatable data="{!v.Caselist}"
        columns="{!v.mycolumns }"
        keyField="id" 
        hideCheckboxColumn="true"
        showRowNumberColumn="true"
        sortedBy="{!v.sortBy}"
        sortedDirection="{!v.sortDirection}"
        onsort="{!c.handleSort}"/>
    
</aura:component>

sortingTableController.Js :

({
    doInit : function(component, event, helper) {
      
        component.set('v.mycolumns', [
            
            {label: 'Case Number', fieldName: 'linkname', type: 'url', sortable :true,       typeAttributes: {label: { fieldName: 'CaseNumber' }, targe: '_blank'}},
            {label: 'Status', fieldName: 'Status', type: 'text', sortable :true},
            {label: 'Created Date ', fieldName: 'CreatedDate', type: 'date', sortable :true}
        ]);

        
        //this method loads data at the time of first loading  only     
        var action = component.get("c.getCases");
        
        action.setCallback(this, function(response) {
            var state = response.getState();
            if (state === "SUCCESS") {
                var Caselist = response.getReturnValue();
                if(Caselist.length > 0){
                    
                    
                    // set Caselist attribute with response
                    component.set("v.Caselist",Caselist);
                                    
                }     
            } 
            else if (state === "ERROR") {
                    var errors = response.getError();
                    if (errors) {
                        if (errors[0] && errors[0].message) {
                            console.log("Error message: " + 
                                        errors[0].message);
                        }
                    } else {
                        console.log("Unknown error");
                    }
                }
        });
        $A.enqueueAction(action);
        
    },
    
   
    //Method gets called by onsort action,
    handleSort: function(component,event,helper){
        var sortBy = event.getParam("fieldName");
  
        var sortDirection = event.getParam("sortDirection");
  
        component.set("v.sortBy",sortBy);
        component.set("v.sortDirection",sortDirection);
        
        helper.sortData(component,sortBy,sortDirection);
    }
})

sortingTableHelper.Js :

({
	sortData : function(component,fieldName,sortDirection){
        var data = component.get("v.Caselist");
        //function to return the value stored in the field
        var key = function(a) { return a[fieldName]; }
        var reverse = sortDirection == 'asc' ? 1: -1;
        
        data.sort(function(a,b){
                var a = key(a) ? key(a) : '';
                var b = key(b) ? key(b) : '';
                return reverse * ((a>b) - (b>a));
            });
        component.set("v.Caselist",data);
    }
})

ControllerForCaseList.cls :

public class ControllerForCaseList {
	@AuraEnabled
    public static List<WrapperCase> getCases(){
        List<WrapperCase> wCase = new List<WrapperCase>();
        for(Case cs : [SELECT Id, Status, CreatedDate, CaseNumber FROM Case LIMIT 15]){
            wCase.add(new WrapperCase(cs));
        }
        return wCase;
    }
    
    //wrapper class
    public class WrapperCase{
        @AuraEnabled
        public String CaseNumber;
        @AuraEnabled
        public String Id;
        @AuraEnabled
        public String linkname;
        @AuraEnabled
        public Datetime CreatedDate;
        
        public WrapperCase(Case cs){
            this.CaseNumber = cs.CaseNumber;
            this.Id = cs.Id;
            this.CreatedDate = cs.CreatedDate;
            this.linkname = 'lightning/r/Case/' + cs.Id +'/view';
        }
    }
}
What’s your Reaction?
+1
0
+1
3
+1
0
+1
0
+1
0
+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.