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
Jonathan Wolff 7Jonathan Wolff 7 

fixed sorting in pagination list with wrapper class

Hello, 
i have a requirement about my List with pagination that uses a wrapper class. I would like to standart order the records by date descending. I tried some code on the internet but i do get errors or it doesnt work. Could you please show me how to impleent it?
 
<aura:component controller="ApexActivityWrapper" implements="force:appHostable,flexipage:availableForAllPageTypes,force:hasRecordId" access="global">

       
    	
        <aura:attribute name="accountList" type="Object" />
        <aura:attribute name="PaginationList" type="Object"/>
    <aura:attribute name="perPageSize" type="Integer" default="10"/>
        <aura:attribute name="totalRecords" type="Integer"/>
    <aura:attribute name="totalPages" type="Integer" default="0"/>
        <aura:attribute name="startValue" type="Integer" />
        <aura:attribute name="endValue" type="Integer"/>
     <aura:attribute name="columns" type="List"/>
     <aura:attribute name="sortedBy" type="String"/>
    <aura:attribute name="sortedDirection" type="String"/>
    <aura:attribute name="isLastPage" type="Boolean"/>
    <aura:attribute name="currentPageNumber" type="Integer" default="1"/>
   

     <aura:handler name="init" action="{!c.doInit}" value="{!this}"/>


    <!-- Ergebnisse + Pagination-->
    
    <div class="slds-grid slds-grid_vertical">
        
        <aura:if isTrue="{!not(empty(v.PaginationList))}">
                 <lightning:datatable data="{!v.PaginationList}" 
                                         columns="{!v.columns}" 
                                         keyField="Id"
                                      	 onsort="{!c.updateSorting}"
                                         sortedBy="{!v.sortedBy}"
                                      	 sortedDirection="{!v.sortedDirection}" 
                                         hideCheckboxColumn="true"
                                      	/>
                <aura:set attribute="else">
                    <div Style="text-align : center"> Keine Aktivitäten
                    </div>
                </aura:set>
            </aura:if>
        
      <lightning:buttongroup>
          
          <lightning:button onclick="{!c.previous}" disabled="{!v.startValue == 0}" label="Previous" iconName='utility:back'/>
          <lightning:button onclick="{!c.next}" disabled="{!v.isLastPage}"  label="Next" iconName='utility:forward'/>
    	
    </lightning:buttongroup>   
      
        
    
</div>
</aura:component>
 
({
    doInit : function(component, event, helper) { 
        
          
        var action = component.get("c.ApexActivityWrapper");
            var recordId = component.get('v.recordId');
        	
            action.setParams({ recordId : recordId });
        action.setCallback(this, function(response) {
            var state = response.getState();
            component.set('v.accountList', response.getReturnValue());
            
            console.log(component.get('v.accountList'));
            //total number of accounts recieved-----------------------------------------
            var lengthVar = component.get("v.accountList").length;
            console.log('length///'+lengthVar);
            component.set("v.totalRecords",lengthVar); 
            //---------------------------------------------------------------------------
            //number of records in each page---------------------------------------------
            var perPage = component.get("v.perPageSize");
            //---------------------------------------------------------------------------
            var values=[];
            console.log('perPage///'+perPage);
            //If total number of records are more than 5 or equals 5-----------------------
            if(lengthVar >= perPage){
                for(var i=0;i<perPage;i++){
                    values.push(response.getReturnValue()[i]);
                }
            }//--------------------------------------------------------------------------
            else{//If total number of records are lesser than 5--------------------------
                for(var i=0;i<lengthVar;i++){
                    values.push(response.getReturnValue()[i]);
                }
            }//--------------------------------------------------------------------------
            console.log('values///'+values);
            component.set("v.PaginationList",values);
            component.set("v.startValue",0);
            //if there are only 5 records or lesser than that in total-------------------
            if(lengthVar <= (component.get("v.startValue")+perPage)){
                component.set("v.isLastPage",true);
            }
            component.set("v.endValue",component.get("v.startValue")+perPage-1); 
        });
        $A.enqueueAction(action);
        component.set('v.columns', 
                      [ {label: 'Status', 			fieldName: '', 															initialWidth: 50, 		cellAttributes: {iconName: {fieldName: 'StatusPicOut' } } },
            //{label: "Datum", 			fieldName: 'DatumOut', 		sortable: true,		type: "date", 			initialWidth: 80, 		typeAttributes:	{month: "2-digit", day: "2-digit", hour: "2-digit", minute: "2-digit", hour12: true } },           
            {label: "Datum", 			fieldName: 'DatumOut', 		sortable: true,		type: "date", 			initialWidth: 110, 		typeAttributes:	{day: '2-digit', month: '2-digit', year: '2-digit', hour: '2-digit', minute: '2-digit', hour12: false } },   
            {label: 'Art', 				fieldName: '', 															initialWidth: 60, 		cellAttributes: {iconName: {fieldName: 'ArtPicOut' } } },
            {label: 'Thema', 			fieldName: 'ThemaIdOut',	sortable: true, 	type: 'url', 			initialWidth: 500,		typeAttributes: {label: {fieldName: 'ThemaOut'}, tooltip: {fieldName: 'TooltipOut'}, target: '_self'} },
            {label: 'Kontakt', 			fieldName: 'KontaktIdOut',	sortable: true, 	type: 'url',									typeAttributes: {label: {fieldName: 'KontaktOut' }, target: '_self'} },
            {label: 'Bezug zu', 		fieldName: 'BezugIdOut',	sortable: true, 	type: 'url',									typeAttributes: {label: {fieldName: 'BezugOut' }, target: '_self'} },
            {label: 'Zugewiesen zu', 	fieldName: 'ZugewiesenOut',	sortable: true,		type: 'text' }, 
                      ]);
    },
                       
        updateSorting: 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);
    },
                       
      
                       
   
    previous : function(component, event, helper){
        component.set("v.isLastPage",false);
        var sObjectList = component.get("v.accountList");
        console.log('sObjectList///',sObjectList);
        var startValue=component.get("v.startValue");
        var endValue=component.get("v.endValue");
        var perPage = component.get("v.perPageSize");
        console.log('startValue///',startValue);
        console.log('endValue///',endValue);
        var totalRecords = component.get("v.totalRecords");
        var values=[];
        for(var i=startValue-perPage;i<startValue;i++){
            console.log('i'+i);
            values.push(sObjectList[i]);
        }
        component.set("v.PaginationList",values);
        component.set("v.startValue",startValue-perPage);
        component.set("v.endValue",startValue-1);
        console.log('start value////'+component.get("v.startValue"));
        console.log('end value////'+component.get("v.endValue"));
    },
    next : function(component, event, helper){
        var sObjectList = component.get("v.accountList");
        console.log('sObjectList///',sObjectList);
        var startValue=component.get("v.startValue");
        var endValue=component.get("v.endValue");
        var perPage = component.get("v.perPageSize");
        console.log('startValue///',startValue);
        console.log('endValue///',endValue);
        var totalRecords = component.get("v.totalRecords");
        var values=[];
        //for eg-------------------------------------------------------------------------
        // this is page 2 and there are 10 records
        // endValue is 4
        //if total no. of records == 4+5+1 (i.e. 10)
        //Or if total no. of records > 10, then evaluate this part----------------------
        if(totalRecords >= endValue+perPage+1){
            for(var i=endValue+1;i<endValue+perPage+1;i++){
                values.push(sObjectList[i]);
            }
            if(totalRecords == endValue+perPage+1){//if total records == 4+5+1-----------
                component.set("v.isLastPage",true);
            }
        }//------------------------------------------------------------------------------
        else{//if total number of records are lesser than 4+5+1(10) i.e. 8
            for(var i=endValue+1;i<totalRecords;i++){
                values.push(sObjectList[i]);
            }
            component.set("v.isLastPage",true);
        }//------------------------------------------------------------------------------
        component.set("v.PaginationList",values);
        component.set("v.startValue",endValue+1);
        component.set("v.endValue",endValue+perPage);
        console.log('start value////'+component.get("v.startValue"));
        console.log('end value////'+component.get("v.endValue"));
    },
    
})
 
({
	    sortData: function (cmp, fieldName, sortDirection) {
        var fname = fieldName;
        var data = cmp.get("v.accountList");
        var reverse = sortDirection !== 'asc';
        data.sort(this.sortBy(fieldName, reverse))
        cmp.set("v.accountList", data);
    },
    sortBy: function (field, reverse) {
        var key = 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));
        }
    },
})
Shri RajShri Raj
To sort the records in the pagination list by date in descending order, you can do the following:
In your Apex wrapper class, add a method that sorts the records by date in descending order and returns the sorted list. For example:

public class ApexActivityWrapper {
    // other methods

    @AuraEnabled
    public static List<Activity> sortByDateDesc(List<Activity> activities) {
        activities.sort((a, b) -> b.ActivityDate.compareTo(a.ActivityDate));
        return activities;
    }
}


In your component's JavaScript controller, call the sortByDateDesc method and pass in the list of records before setting it to the PaginationList attribute. Also, set the sortedBy attribute to "ActivityDate" and the sortedDirection attribute to "desc" so that the lightning:datatable component will display the sorted records.

({
    doInit : function(component, event, helper) { 
        var action = component.get("c.ApexActivityWrapper");
        var recordId = component.get('v.recordId');
        action.setParams({ recordId : recordId });
        action.setCallback(this, function(response) {
            var state = response.getState();
            var activities = response.getReturnValue();
            activities = helper.sortByDateDesc(activities);
            component.set("v.accountList", activities);
            component.set("v.sortedBy", "ActivityDate");
            component.set("v.sortedDirection", "desc");
            // ... rest of the pagination code
        });
        $A.enqueueAction(action);
    },
    // ...
})


In your component's JavaScript helper, create the sortByDateDesc method that calls the sortByDateDesc method in the Apex wrapper class and pass in the list of records, then set the returned value to the PaginationList attribute.

({
    sortByDateDesc : function(component, event, helper, activities) {
        var action = component.get("c.sortByDateDesc");
        action.setParams({ activities : activities });
        action.setCallback(this, function(response) {
            var state = response.getState();
            if (state === "SUCCESS") {
                var sortedActivities = response.getReturnValue();
                component.set("v.PaginationList", sortedActivities);
            }
        });
        $A.enqueueAction(action);
    },
    // ...
})