Sample Code:
Component:
Component:
- <aura:component implements=“force:appHostable”
- controller=“AccountListController”>
- <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>
Component Controller:
- ({
- fetchAccounts : function( component, event, helper ) {
- component.set( ‘v.mycolumns’, [
- {label: ‘Account Name’, fieldName: ‘linkName’, type: ‘url’, sortable: true,
- typeAttributes: {label: { fieldName: ‘Name’ }, target: ‘_blank’}},
- {label: ‘Industry’, fieldName: ‘Industry’, type: ‘text’, sortable: true},
- {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” ) {
- var records =response.getReturnValue();
- records.forEach( function( record ){
- record.linkName = ‘/’ + record.Id;
- });
- component.set( “v.acctList”, records );
- helper.sortData( component, component.get( “v.sortedBy” ), component.set( “v.sortedDirection” ) );
- }
- });
- $A.enqueueAction(action);
- },
- updateColumnSorting: function (cmp, event, helper) {
- var fieldName = event.getParam( ‘fieldName’ );
- cmp.set( “v.sortedBy”, fieldName );
- if ( fieldName === ‘linkName’ )
- fieldName = ‘Name’;
- var sortDirection = event.getParam( ‘sortDirection’ );
- cmp.set( “v.sortedDirection”, sortDirection );
- helper.sortData( cmp, fieldName, sortDirection );
- }
- })
Component Helper:
- ({
- 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 ) );
- }
- }
- })
Apex Class:
- public class AccountListController {
- @AuraEnabled
- public static List < Account > fetchAccts() {
- return [ SELECT Id, Name, Industry, Type, CreatedDate
- FROM Account
- LIMIT 100 ];
- }
- }
Output: