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
Sushma_RaoSushma_Rao 

How to sort wrapper class list ?

Hi all,

 

I have a wrapper class which contains a list of sobjects, i want to have th sorting on the fields of these objects in the wrapper list:

The apex code is as follows:

Class jobsWrapper
{
public JobSuite__Job__c job {get;set;}
public JobSuite__Job_Task__c jobTasks{get;set;}
public JobsWrapper(JobSuite__Job__c objjobs, JobSuite__Job_Task__c objjobTasks)
{
// if(jobTasks== NULL){jobTasks = new List<Job_Task__c>();}
job = objjobs;
jobTasks = objjobTasks;
}

public JobsWrapper()
{
if(jobTasks== NULL){jobTasks = new JobSuite__Job_Task__c();}
if(job == NULL){job = new JobSuite__Job__c();}
 
}
}

 

i want to allow sorting the wrapper list by the fields in the job - like client, jobname, jobnumber etc and fields from the task object as taskname, reviseddue dateetc.

 

How can i do this?

Please help, thanks in advance.

harsha__charsha__c

Hi Sushma,

 

There are some ways to sort the list of Sobject.

 

1. You can make a query using the order by  keyword and assign the result to the list

 

              - If the list is formed already, then you can take the record Ids from that list into a set and in the query mention "where Id                                                     IN : set AND order by Name/..."  

              

2. you can add the records into a map. The map should be like : key as the Field (on which field basis you want to sort) and the value is SObject

           

            - Now the map is formed and the keyset of the map can be  sorted . When keys are sorted obviously the values also will get sorted.

 

            - Now take the map values into a list.

 

 

Thus you can get the sorted list.

Sushma_RaoSushma_Rao

Thanks harsha for the reply,
I have two objects in the list job and job task. Job is master and the job task is detail. In the query i am getting the records for the job, then in another query i am getting the job tasks for each job and i have a function to create the wrapper and add these two object, i am adding one job and then the task for the job which has the latest revised due date.

Sorting for the toher columns is fin but for the task columns if i sort in the query then i get the tasks with not the which has the latest revised due date. How should i handle this?

The function for the wrapper add is as follows:::

 

 public PageReference ViewData() {
    
    string str1='';
    string str2='';
    
     string sortFullExp = sortExpression  + ' ' + sortDirection;
     system.debug('string of sortFullExp $$$$$$$$$$$$$$$$$$$$$$$$ '+sortFullExp);
      userName=UserInfo.getName();
      system.debug('********'+userName);
      
    if(sortExpression == 'JobSuite__Job__r.Name'){
        str1 = 'ORDER by Name '+sortDirection;
    }
    else if(sortExpression == 'JobSuite__Job_Auto_Number__c'){
       str1 = 'ORDER by JobSuite__Job_Auto_Number__c '+sortDirection;
       // str2 = ', JobSuite__Job__r.JobSuite__Job_Auto_Number__c '+sortDirection; 
    }
    else if(sortExpression == 'JobSuite__JS_Client__c'){
       str1 = 'ORDER by JobSuite__JS_Client__c '+sortDirection;
    }
    else if(sortExpression == 'JobSuite__Status__c'){
       str1 = 'ORDER by JobSuite__Status__c '+sortDirection;
    }
    else if(sortExpression == 'JobSuite__Due_Date__c'){
       str1 = 'ORDER by JobSuite__Due_Date__c '+sortDirection;
    }
    else if(sortExpression == 'JobSuite__Job_Task__r.Name'){
       str2 = ',Name '+sortDirection;
    }
    else if(sortExpression == 'JobSuite__Revised_Due_Date__c'){
       str2 = ',JobSuite__Revised_Due_Date__c '+sortDirection;
    }
    else if(sortExpression == 'JobSuite__Revised_Due_Date__c'){
       str2 = ''+sortDirection;
    }
         
    system.debug('job order string -----------'+str1);
    system.debug('job task order string -----------'+str2);
    
      TeamList = [select Name, JobSuite__Staff__c,JobSuite__Job__c from JobSuite__Job_Team__c where JobSuite__Staff__c = : userName];
       
      for( JobSuite__Job_Team__c jteam : TeamList)
      {
          stJobId.add(jteam.JobSuite__Job__c);
          system.debug('***job******'+stJobId);
      }
      string st1 = 'Active';
      joblist = database.query('select Name, JobSuite__Job_Auto_Number__c, JobSuite__JS_Client__c, JobSuite__Status__c, JobSuite__Due_Date__c from JobSuite__Job__c  where Id IN : stJobId and JobSuite__Status__c=: st1 '+str1);
      system.debug('***job list count ******'+joblist.size());
   
      boolean st2 = false;
      List <JobSuite__Job_Task__c> jobTasks = Database.query('select id,Name,JobSuite__Revised_Due_Date__c,JobSuite__Job__r.Name,JobSuite__Job__r.JobSuite__Job_Auto_Number__c from JobSuite__Job_Task__c where JobSuite__Job__r.Id IN: stJobId and JobSuite__Marked_Done__c =: st2 order by JobSuite__Revised_Due_Date__c '+str2);
      system.debug('@@@@@@@@@'+jobTasks);
      
      jWrapper = new List<jobsWrapper>();
      Map <Id,JobSuite__Job_Task__c> mapTask = new Map<Id,JobSuite__Job_Task__c>();
      //List <JobSuite__Job_Task__c> jTask = Database.query('select id, Name ,JobSuite__Revised_Due_Date__c,JobSuite__Job__r.Name from JobSuite__Job_Task__c where JobSuite__Job__c IN : stJobId order by JobSuite__Revised_Due_Date__c ASC ' +str2);
      //system.debug('******JTask********'+jTask);
      string q = 'select id, Name ,JobSuite__Revised_Due_Date__c,JobSuite__Job__r.Name from JobSuite__Job_Task__c where JobSuite__Job__c IN:stJobId  order by '+sortFullExp; 
      system.debug('query++++++++++++ '+q);

      integer cnt;
      id vjobId; 
      for(JobSuite__Job_Task__c objobtask:jobTasks)
        {
          system.debug('***mapTask***'+objobtask.JobSuite__Job__r.id);
           if(vjobId != objobtask.JobSuite__Job__r.Id)
           {
               system.debug('Job Name in %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% '+objobtask.JobSuite__Job__r.Name);
               mapTask.put(objobtask.JobSuite__Job__r.id,objobtask);
         
           vjobId = objobtask.JobSuite__Job__r.Id;
           }  
        }

         cnt = mapTask.size();
         system.debug('***Mapsize**'+cnt);
      
      
       jWrapper = new List<jobsWrapper>();
       for(JobSuite__Job__c jb:joblist)
       {
           JobsWrapper jobWrap = new JobsWrapper();
           jobWrap.job = jb;
           jobWrap.jobTasks= mapTask.get(jb.id);
           jWrapper.add(jobWrap );
           system.debug('Job Name in wrapper%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% '+jobWrap.job.Name);
       }
       
       return null;
       }

 

Please help thanks, Thanks in advance.

 

 

liron169liron169

I think there is better way- using Comparable interface.

In your case it'll be something like this:

 

 

 

 

 

public static String compareField {get; set;}    //let the user to update this field from the page


Class jobsWrapper implements Comparable
{
public JobSuite__Job__c job {get;set;}
public JobSuite__Job_Task__c jobTasks{get;set;}
public JobsWrapper(JobSuite__Job__c objjobs, JobSuite__Job_Task__c objjobTasks)
{
// if(jobTasks== NULL){jobTasks = new List<Job_Task__c>();}
job = objjobs;
jobTasks = objjobTasks;
}

public JobsWrapper()
{
if(jobTasks== NULL){jobTasks = new JobSuite__Job_Task__c();}
if(job == NULL){job = new JobSuite__Job__c();}
 
}

public Integer compareTo(Object jobWrp)
{
jobsWrapper comparejobWrp = (jobsWrapper)jobWrp;
            
if((String)job.get(compareField) > (String)compareToRL.job.get(compareField))
    1;
else
    0;
}
}

harsha__charsha__c

Ohk.

 

Here the second way will help you (from the 2 ways I suggested in my earlier post).

 

See, however one wrapper class instance is having both job and it's task. And the wrapper instance is added to the list.

 

Iterate through that list and put the values into the map as followed.

 

     - Key as the field that you wanted to get sorted

 

     - Value will be the wrapper class instance i.e. the listWrapper[0], [1], [2], ....

 

Now you can sort the keyset of the map and obviously the values are also ordered in the same way as of the keys.

 

Finally add all the map values to the list if wrapper.

Sushma_RaoSushma_Rao

Thanks all for the quick reply,

 

I used the comparable inteface and was able to sort the list in the ascending order, but i also want to sort the columns in the descending order, as well i want to sort the list on the date fields too.

How can I sort the list in the descending order as well as on the date fields?

 

Please reply,

Thanks in advance.

Mad DeveloperMad Developer

Hey, can you please tell me what is the comparable interface and how to use it?

liron169liron169

You'll need another variable in your controller , e.g. SortOrder, and change it from 'asc' to 'desc' and vice versa each time.

 

Than, in the compareTo function you can write:

 

if((String)job.get(compareField) > (String)compareToRL.job.get(compareField))
    return SortOrder.equals('asc') ? 1 : 0;
else
     return SortOrder.equals('asc') ? 0 : 1;

liron169liron169

Mad Developer, The comparable interface is the same as in java.

 

you can read here:

http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/Comparable.html

Mad DeveloperMad Developer

Thanks lironand I am Toddman.

Sushma_RaoSushma_Rao

Thanks all for the reply, but i am still not able to do the sorting as my wrapper class the variables are static they will not be updated with a new value in the sorting, my code for the sorting is as follows:

public with sharing class JobsListViewHome1 {

    public list<JobSuite__Job__c> joblist{get;set;}
    public list<JobSuite__Job_Task__c> TaskList{get;set;}
    Public List <JobSuite__Job_Task__c> jobTasks{get; set;}
    public list<JobSuite__Job_Task_Role__c> RoleList{get;set;}
    public list<JobSuite__Job_Team__c> TeamList{get;set;}
    public list<jobsWrapper> jWrapper {get;set;}
    public string userName;
    public Set <Id> stJobId=new Set<Id>();
     public static string sortOrder1 = 'ASC';
    
    private String sortExp = 'JobSuite__Job__r.Name';
    private String sortDirection = 'ASC';
    public static String sortBy1  = 'JobSuite__Job__r.Name';
   // public String sortOrder1= 'ASC';
   
     
 public Class jobsWrapper implements Comparable
   {
        public JobSuite__Job__c job {get;set;}
        public JobSuite__Job_Task__c jobTasks{get;set;}
                
        public JobsWrapper(JobSuite__Job__c objjobs, JobSuite__Job_Task__c objjobTasks)
           {
            // if(jobTasks== NULL){jobTasks = new List<Job_Task__c>();}
             job = objjobs;
             jobTasks = objjobTasks;     
            }
         
         public JobsWrapper()
           {
             if(jobTasks== NULL){jobTasks = new JobSuite__Job_Task__c();}
              if(job == NULL){job = new JobSuite__Job__c();}
            //// job = objjobs;
//jobTasks = objjobTasks;     
            }
           
     public   Integer compareTo(Object compareTo1)
         {
            jobsWrapper compareTo2 = (jobsWrapper)compareTo1;
            if (sortBy1.equals('JobSuite__JS_Client__c'))
            {
                ///return job.JobSuite__JS_Client__r.Name.compareTo(compareTo2.job.JobSuite__JS_Client__r.Name);   
                if((String)job.JobSuite__JS_Client__r.Name > (String)compareTo2.job.JobSuite__JS_Client__r.Name)
                {
                    return null;//sortOrder1.equals('ASC') ? 1 : 0;
                }
                else
                {
                     return null;//sortOrder1.equals('ASC') ? 0 : 1;
                }    
            }
             else if (sortBy1.equals('JobSuite__Job__r.Name'))
            {
               ////return job.Name.compareTo(compareTo2.job.Name);
               if((String)job.Name > (String)compareTo2.job.Name)
                {
                    return sortOrder1.equals('ASC') ? 1 : 0;
                }
                else
                {
                     return sortOrder1.equals('ASC') ? 0 : 1;
                }       
            }
             else if (sortBy1.equals('JobSuite__Job_Task__r.Name'))
            {
               ////return jobTasks.Name.compareTo(compareTo2.jobTasks.Name);  
               if((String)jobTasks.Name > (String)compareTo2.jobTasks.Name)
                {
                    return sortOrder1.equals('ASC') ? 1 : 0;
                }
                else
                {
                     return sortOrder1.equals('ASC') ? 0 : 1;
                }      
            }
             else if (sortBy1.equals('JobSuite__Status__c'))
            {
               ////return job.JobSuite__Status__c.compareTo(compareTo2.job.JobSuite__Status__c);
                if((String)jobTasks.Name > (String)compareTo2.jobTasks.Name)
                {
                    return sortOrder1.equals('ASC') ? 1 : 0;
                }
                else
                {
                     return sortOrder1.equals('ASC') ? 0 : 1;
                }     
            }
            else if (sortBy1.equals('JobSuite__Job_Auto_Number__c'))
            {
               /////return job.JobSuite__Job_Auto_Number__c.compareTo(compareTo2.job.JobSuite__Job_Auto_Number__c);    
                if((String)job.JobSuite__Job_Auto_Number__c > (String)compareTo2.job.JobSuite__Job_Auto_Number__c)
                {
                    return sortOrder1.equals('ASC') ? 1 : 0;
                }
                else
                {
                     return sortOrder1.equals('ASC') ? 0 : 1;
                }  
            }
           /* else if (JobsListViewHome1.sortBy.equals('JobSuite__Due_Date__c'))
            {
               return job.JobSuite__Revised_Due_Date__c.compareTo(compareTo2.job.JobSuite__Revised_Due_Date__c);    
            }*/
            else
            {
            return null;
            }
            
         }
     
     }
     
    public JobsListViewHome1()
    {
        ViewData();   
    }
    
     public String sortExpression
     {
        get
        {
            return sortExp;
        }
        set
        {
            // if the columns is clicked on then switch between ascending and descending modes
            if( value == sortExp)
            {
                sortDirection = (sortDirection== 'ASC')?'DESC' : 'ASC';
            }
            else
            {
                sortDirection='ASC';
            }
            sortExp=value;
        }
    }
    public String sortBy
     {
        get
        {
            return sortBy1;
        }
        set
        {
            // if the columns is clicked on then switch between ascending and descending modes
            if( value == sortBy1)
            {
                sortOrder1 = (sortOrder1== 'ASC')?'DESC' : 'ASC';
            }
            else
            {
                sortOrder1='ASC';
            }
            sortBy1=value;
        }
    }
    
    public string getSortDirection()
    {
        // if not columns is selected
        if(sortExpression==NULL || sortExpression=='')
        {
            return 'ASC';
        }
        else
        {
            return sortDirection;
        }
    }
    
     public void setSortDirection(String value)
    {
        sortDirection=value;
    }
    public string getsortOrder()
    {
        // if not columns is selected
        if(sortBy1 ==NULL || sortBy1 =='')
        {
            return 'ASC';
        }
        else
        {
            return sortOrder1;
        }
    }
    
     public void setsortOrder(String value)
    {
        sortOrder1=value;
    }
    
    public PageReference ViewData() {
    
    string str1='';
    string str2='';
    
     string sortFullExp = sortExpression  + ' ' + sortDirection;
     system.debug('string of sortFullExp $$$$$$$$$$$$$$$$$$$$$$$$ '+sortFullExp);
      userName=UserInfo.getName();
      system.debug('********'+userName);
      
    /*if(sortExpression == 'JobSuite__Job__r.Name'){
        sortBy = 'Name';
        
    }
    else if(sortExpression == 'JobSuite__Job_Auto_Number__c'){
       sortBy = 'JobNumber';      
    }
    else if(sortExpression == 'JobSuite__JS_Client__c'){
       sortBy = 'Client';
    }
    else if(sortExpression == 'JobSuite__Status__c'){
       sortBy = 'Status';
    }
    else if(sortExpression == 'JobSuite__Due_Date__c'){
       sortBy = 'DueDate';
    }
    else if(sortExpression == 'JobSuite__Job_Task__r.Name'){
       sortBy = 'TaskName';
    }
    else if(sortExpression == 'JobSuite__Revised_Due_Date__c'){
       sortBy = 'RevisedDate';
    }*/
    
         
    system.debug('job order string -----------'+str1);
    system.debug('job task order string -----------'+str2);
    
      TeamList = [select Name, JobSuite__Staff__c,JobSuite__Job__c from JobSuite__Job_Team__c where JobSuite__Staff__c = : userName];
       
      for( JobSuite__Job_Team__c jteam : TeamList)
      {
          stJobId.add(jteam.JobSuite__Job__c);
          system.debug('***job******'+stJobId);
      }
      string st1 = 'Active';
      joblist = database.query('select Name, JobSuite__Job_Auto_Number__c, JobSuite__JS_Client__c,JobSuite__JS_Client__r.Name, JobSuite__Status__c, JobSuite__Due_Date__c from JobSuite__Job__c  where Id IN : stJobId and JobSuite__Status__c=: st1 ');//+str1);
      system.debug('***job list count ******'+joblist.size());
   
      boolean st2 = false;
      List <JobSuite__Job_Task__c> jobTasks = Database.query('select id,Name,JobSuite__Revised_Due_Date__c,JobSuite__Job__r.Name,JobSuite__Job__r.JobSuite__Job_Auto_Number__c from JobSuite__Job_Task__c where JobSuite__Job__r.Id IN: stJobId and JobSuite__Marked_Done__c =: st2 order by JobSuite__Revised_Due_Date__c ');//+str2);
      system.debug('@@@@@@@@@'+jobTasks);
      
      jWrapper = new List<jobsWrapper>();
      Map <Id,JobSuite__Job_Task__c> mapTask = new Map<Id,JobSuite__Job_Task__c>();
      //List <JobSuite__Job_Task__c> jTask = Database.query('select id, Name ,JobSuite__Revised_Due_Date__c,JobSuite__Job__r.Name from JobSuite__Job_Task__c where JobSuite__Job__c IN : stJobId order by JobSuite__Revised_Due_Date__c ASC ' +str2);
      //system.debug('******JTask********'+jTask);
      //string q = 'select id, Name ,JobSuite__Revised_Due_Date__c,JobSuite__Job__r.Name from JobSuite__Job_Task__c where JobSuite__Job__c IN:stJobId  order by '+sortFullExp;
      //system.debug('query++++++++++++ '+q);

      integer cnt;
      id vjobId;
      for(JobSuite__Job_Task__c objobtask:jobTasks)
        {
          system.debug('***mapTask***'+objobtask.JobSuite__Job__r.id);
           if(vjobId != objobtask.JobSuite__Job__r.Id)
           {
               system.debug('Job Name in %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% '+objobtask.JobSuite__Job__r.Name);
               mapTask.put(objobtask.JobSuite__Job__r.id,objobtask);
         
           vjobId = objobtask.JobSuite__Job__r.Id;
           }  
        }

         cnt = mapTask.size();
         system.debug('***Mapsize**'+cnt);
      
      
       jWrapper = new List<jobsWrapper>();
       for(JobSuite__Job__c jb:joblist)
       {
           JobsWrapper jobWrap = new JobsWrapper();
           jobWrap.job = jb;
           jobWrap.jobTasks= mapTask.get(jb.id);
           jWrapper.add(jobWrap);
           system.debug('Job Name in wrapper%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% '+jobWrap.job.Name);
       }
       jWrapper.sort();
       return null;
       }
  }

 The problem is I am sorting the collumns by ascending at frst then on click on the collumn to sort the collumns in the descending order.

Please suggest some way to do this.

Thanks in advance.

 

 

liron169liron169

hi,

 

looks a little "messi".

 

When I did it I use only 2 variable:

public static String comparedField {get; set;}

public static String sortOrder {
        get {
            if(sortOrder== null)
                sortOrder='asc';
            return sortOrder;
        }
        set;
    }

 

 

I change both of them when the user click on column header in the page.

 

<apex:column>
                                <apex:facet name="header">
                                    <apex:commandLink value="ColumnsName" action="{!sortFunction}" rerender="results">
                                        <apex:param name="compareField" value="fieldName" assignTo="{!compareField}" />
                                        <apex:param name="sortOrder" value="{!IF(sortOrder='asc', 'desc', 'asc')}" assignTo="{!sortOrder}" />
                                    </apex:commandLink>
                                </apex:facet>
                                <apex:outputField value="{!b.fieldName}" />
                            </apex:column>