function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
raghavendra kiran 9raghavendra kiran 9 

Datatable sorting is getting as irregular o/p of both asc and desc

<aura:component controller='AccountDataTable8' implements='force:appHostable'>
    <!--attribute -->
    <aura:attribute name='myData' type='object' />
    <aura:attribute name='myColumns' type='list'/>
    <aura:attribute name='limitRows' type='integer' default='5'/>
    <aura:attribute name='offsetLimit' type='integer' default='0'/>
    <aura:attribute name='countRows' type='integer' default='5'/>
    <aura:attribute name='sortBy' type='string'/>
    <aura:attribute name='sortByDirection' type='string' />
    <aura:attribute name="defaultSortDirection" type="string"/>
    <!-- /attribute -->
    <!--handler -->
    <aura:handler name='init' value='{!this}' action='{!c.show}'/>
    <!--/handler -->
    <div class='slds-m-around__xx-small' style='height:180px'>      
        <lightning:datatable data='{!v.myData}' columns='{!v.myColumns}' keyField ='Id' 
                              onsort='{!c.handleSort}' sortedBy='{!v.sortBy}' 
                             sortedDirection='{!v.sortByDirection}'
                              defaultSortDirection="{!v.defaultSortDirection }"/>  
                  </div>
      </lightning:card>
</aura:component>

controller===
({
    show : function(component, event, helper) {
        helper.one(component);
    },
 handleSort:function(component,event,helper){
          var fieldName = event.getParam('fieldName');
        var sortDirection = event.getParam('sortDirection');
        // assign the latest attribute with the sorted column fieldName and sorted direction
       component.set("v.sortBy", fieldName);
       component.set("v.sortByDirection", sortDirection);
        helper.sort(component, fieldName, sortDirection);
}
})
helper===
({
    one : function(component) {
       var actionRow =[
            {label:'NEW',name:'NEW'},
            {label:'EDIT',name:'EDIT'},
            {label:'VIEW',name:'VIEW'},
            {label:'DELETE',name:'DELETE'}
        ];
        component.set('v.myColumns',[
            {label:'AccountName',fieldName:'AccountName',sortable:true,type:'url',
             typeAttributes:{label:{fieldName:'Name'},target:'_blank'}},
            {label:'Type',fieldName:'Type',type:'text',sortable:true},
            {label:'Phone',fieldName:'Phone',type:'phone'},
            {type:'action',typeAttributes:{rowActions:actionRow}}
        ]);
        var getaccs = component.get('c.getAllAccountsVar');
       // var limit =component.get('v.limitRows');
        getaccs.setParams({
            'intLimit':component.get('v.limitRows'),
            'intOffset':component.get('v.offsetLimit')
        }); 
        getaccs.setCallback(this,function(response){
            var state = response.getState();
            if(state==='SUCCESS'){
                var results = response.getReturnValue();
                results.forEach(function(record){
                    record.AccountName = '/'+record.Id; 
                    
                });
                component.set('v.myData',results);
                component.set('v.offsetLimit',component.get('v.countRows'));
                 component.set('v.loadMoreStatus','Scroll To Load Data');
            }else{
                alert('error is here ');
            }
        });
        $A.enqueueAction(getaccs);
    }
 sort:function(component,fieldName,sortDirection){
         var data = component.get("v.myData");
        var reverse = sortDirection !== 'asc';
        //sorts the rows based on the column header that's clicked
        data.sort(this.sortBy(fieldName, reverse))
        component.set("v.myData", data);
 },
    sortBy:function(field,reverse,primer){
 var key = primer ?
            function(x) {return primer(x[field])} :
            function(x) {return x[field]};
        //checks if the two rows should switch places
        reverse = !reverse ? 1 : -1;
        return function (a, b) {
            return a = key(a), b = key(b), reverse * ((a > b) - (b > a));
        }
    }
    
})

public class AccountDataTable8 {
@AuraEnabled
    public static list<account> getAllAccountsVar(integer intLimit,integer intOffset){
        integer limitvar = integer.valueOf(intLimit);
        integer offsetvar = integer.valueOf(intOffset);
        list<account> acc=[select id,Name,type,phone from account limit:limitvar offset:offsetvar];
        return acc;
    }

 
Best Answer chosen by raghavendra kiran 9
raghavendra kiran 9raghavendra kiran 9
in order to getrid of above statement i used the RowLevelActions...  :)

All Answers

Khan AnasKhan Anas (Salesforce Developers) 
Hi Raghavendra,

Greetings to you!

You need to use fieldName:'Name' instead of fieldName:'AccountName'
You have to use the API name of the field while setting columns of datatable. So, use label:'AccountName',fieldName:'Name',sortable:true,type:'url',

Apart from this, your code looks good to me. I have tested in my org and it is working fine. This is the corrected Helper code:
 
({
    one : function(component) {
        var actionRow =[
            {label:'NEW',name:'NEW'},
            {label:'EDIT',name:'EDIT'},
            {label:'VIEW',name:'VIEW'},
            {label:'DELETE',name:'DELETE'}
        ];
        component.set('v.myColumns',[
            {label:'AccountName',fieldName:'Name',sortable:true,type:'url',
             typeAttributes:{label:{fieldName:'Name'},target:'_blank'}},
            {label:'Type',fieldName:'Type',type:'text',sortable:true},
            {label:'Phone',fieldName:'Phone',type:'phone'},
            {type:'action',typeAttributes:{rowActions:actionRow}}
        ]);
        var getaccs = component.get('c.getAllAccountsVar');
        // var limit =component.get('v.limitRows');
        getaccs.setParams({
            'intLimit':component.get('v.limitRows'),
            'intOffset':component.get('v.offsetLimit')
        }); 
        getaccs.setCallback(this,function(response){
            var state = response.getState();
            if(state==='SUCCESS'){
                var results = response.getReturnValue();
                results.forEach(function(record){
                    record.AccountName = '/'+record.Id; 
                    
                });
                component.set('v.myData',results);
                component.set('v.offsetLimit',component.get('v.countRows'));
                component.set('v.loadMoreStatus','Scroll To Load Data');
            }else{
                alert('error is here ');
            }
        });
        $A.enqueueAction(getaccs);
    },
    
    sort:function(component,fieldName,sortDirection){
        var data = component.get("v.myData");
        var reverse = sortDirection !== 'asc';
        //sorts the rows based on the column header that's clicked
        data.sort(this.sortBy(fieldName, reverse))
        component.set("v.myData", data);
    },
    
    sortBy:function(field,reverse,primer){
        var key = primer ?
            function(x) {return primer(x[field])} :
        function(x) {return x[field]};
        //checks if the two rows should switch places
        reverse = !reverse ? 1 : -1;
        return function (a, b) {
            return a = key(a), b = key(b), reverse * ((a > b) - (b > a));
        }
    }
    
})

I hope it helps you.

Kindly let me know if it helps you and close your query by marking it as solved so that it can help others in the future. It will help to keep this community clean.

Thanks and Regards,
Khan Anas
raghavendra kiran 9raghavendra kiran 9
Thanks alot for your Quick Response,

I used the AccountName instead of FieldName because in the type Attributes I mentioned the FieldName:Name i.e
typeAttributes:{label:{fieldName:'Name'},target:'_blank'}},  so that i can link the recordId to the Name, if we click the Name then it will be redirected to the destination record.you can find it in the code line number 26 and 27, by this if we use the AccountName in the FieldName then sorting is Not working, if we use the Name(Api) then line number 27 is not working i.e redirection of record.

so once you check the code by changing  the FieldName to AccountName, you can find it by clicking the AccountName you will be redirected to the RecordView..but sorting doesnot work, and if you change the AccountName to Name then Destination to record View doesn't work...but Sorting Works.if we change the AccountName from line number 27 to Name(Api) then we get the RecordId instead of name of the account under the AccountName Column.

so kindly check it once and reply

Regards
Raghavendra
raghavendra kiran 9raghavendra kiran 9
in order to getrid of above statement i used the RowLevelActions...  :)
This was selected as the best answer