Lighting Data Table Sorting Example

AccountList.cmp

<aura:component controller="AccountListController"
                implements="flexipage:availableForAllPageTypes,lightning:actionOverride,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:appHostable" >
    
    <aura:attribute type="Account[]" name="acctList"/>
    <aura:attribute name="mycolumns" type="List"/>
    <aura:attribute name="sortedBy" type="String" default="Name"/>
    <aura:attribute name="sortedDirection" type="String" default="asc"/>
    
    <aura:handler name="init" value="{!this}" action="{!c.fetchAccounts}"/>
    
    <lightning:datatable data="{!v.acctList}" 
                         columns="{!v.mycolumns}" 
                         keyField="id"
                         hideCheckboxColumn="true"
                         onsort="{!c.updateColumnSorting}"
                         sortedBy="{!v.sortedBy}"  
                        sortedDirection="{!v.sortedDirection}"/>
    
</aura:component>

AccountListController.js

({
    fetchAccounts : function(component, event, helper) {
        component.set('v.mycolumns', [
            {label: 'Account Name', fieldName: 'Name', type: 'text', sortable: true},
            {label: 'Industry', fieldName: 'Industry', type: 'text'},
            {label: 'Type', fieldName: 'Type', type: 'Text'}
        ]);
        var action = component.get("c.fetchAccts");
        action.setParams({
        });
        action.setCallback(this, function(response){
            var state = response.getState();
            if (state === "SUCCESS") {
                component.set("v.acctList", response.getReturnValue());
                helper.sortData(component, component.get("v.sortedBy"), component.get("v.sortedDirection"));
            }
        });
        $A.enqueueAction(action);
    },
    updateColumnSorting: function (cmp, event, helper) {
        var fieldName = event.getParam('fieldName');
        var sortDirection = event.getParam('sortDirection');
        cmp.set("v.sortedBy", fieldName);
        cmp.set("v.sortedDirection", sortDirection);
        helper.sortData(cmp, fieldName, sortDirection);
    }
})

AccountListHelper.js:

({
    sortData: function (cmp, fieldName, sortDirection) {
        var data = cmp.get("v.acctList");
        var reverse = sortDirection !== 'asc';
        data.sort(this.sortBy(fieldName, reverse))
        cmp.set("v.acctList", data);
    },
    sortBy: function (field, reverse, primer) {
        var key = primer ?
            function(x) {return primer(x[field])} :
            function(x) {return x[field]};
        reverse = !reverse ? 1 : -1;
        return function (a, b) {
            return a = key(a), b = key(b), reverse * ((a > b) - (b > a));
        }
    }
})

AccountListController apex class:

public class AccountListController {

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

Output:


2 comments:

  1. Hi,

    I am implementing the Sorting functionality. I used same code like yours. So when component loads I get the default column sorted. but Onsort event is not firing in my component. I cant see direction arrow(-->) like you showed in the your screen shot after Account name.
    Let me know if you think I have to add something more to create Onsort event.

    Thanks,
    Saurabh

    ReplyDelete