How to Sort an Apex class Object List

[Edit : Now there is an interface natively provided by salesforce to sort the class object lists]

I recently needed to sort an apex class object List which was retrieved through a webservice callout as it could not be sorted at the service end.

This is the apex method which was used to build it

 public void testsort(){
map<string,List> stracc = new map<string,list>();
for(accClass a:accClassobj ){
if(stracc.containsKey(a.name))
                stracc.get(a.name).add(a);
else
stracc.put(a.name,new accclass[]{a});
}
accclassobj= new list();
list nameList = new list();
nameList.addAll(stracc.keyset());
nameList.sort();
for(string s:nameList){
accclassobj.addAll(stracc.get(s));
}

Above is the code involved in sorting to build a map with object parameter as the key by which we gonna sort and List.

 

How to Filter list alphabetically

How to Filter list alphabetically

There was a requirement where i needed to build a list which can be filtered based on the starting alphabet. And also the List needs to remember the selections made as we move through other pages.


|

Please wait…

In the VF page i am displaying the List ‘CurrentLsit‘ which would hold the contact list with checkbox which is paginated and ‘DisplaySelectedList‘ which would remember the selected contact. Array Alphabet is used in repeat to build the link of alphabets at the top of page

Controller method

 
 
public with sharing class Pagin_alpha {    
    private List contactSetList{get;set;}
    private string contactListQuery;
    private set selectedContact;
   
    public List alphabet{get;set;}
    public boolean fals{get;set;}  
   
    public Pagin_alpha(){
      fals=false;
      alphabet=new string[]{‘All’,’a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’, ‘g’, ‘h’, ‘i’, ‘j’, ‘k’, ‘l’, ‘m’, ‘n’, ‘o’, ‘p’, ‘q’, ‘r’, ‘s’, ‘t’, ‘u’, ‘v’, ‘w’, ‘x’, ‘y’, ‘z’ }; 
      contactSetList = new List();
      selectedContact = new set();
      contactListQuery= ‘select id,name,phone from contact limit 1000’;   
    }
   
     Private void updateSelectedContact(){
        for(contactSet cs:contactSetList ){
           if(cs.checked)
               selectedcontact.add(cs.ocontact);
           else{
               if(selectedcontact.contains(cs.ocontact))
                   selectedcontact.remove(cs.ocontact);
               }
       }  
    }
   
      public ApexPages.StandardSetController standardSetCon {
        get {
            if(standardSetCon == null) {
                standardSetCon = new ApexPages.StandardSetController(Database.getQueryLocator(contactListQuery));
                // sets the number of records in each page set
                standardSetCon .setPageSize(20);
            }
            return standardSetCon ;
        }
        set;
    }
 
    public List getCurrentList() {
       updateSelectedContact();
       contactSetList = new List();      
        for (contact category : (List)standardSetCon.getRecords()){       
            if(selectedContact.contains(category))         
            contactSetList.add(new contactSet(category,’true’));
            else
            contactSetList.add(new contactSet(category));
        }
        fals=false;
        return contactSetList;
    }
   
    public PageReference refreshList2() {      
       standardSetCon = null;    
       string s;
       if(apexpages.currentpage().getparameters().get(‘alpha’) == ‘All’)
           s=’%’;
       else
           s= apexpages.currentpage().getparameters().get(‘alpha’)+’%’;
      
       contactListQuery= ‘select id,name,phone from contact where name like’ +”’+s +”’+ ‘limit 5000’;          
        return null;
    }
   
  
   
    public List getDisplaySelectedList(){
        updateSelectedContact();
        List displaycon = new list();
        displaycon.addall(selectedcontact);
        return displaycon;
    }
      
    public class contactSet {
        public Boolean checked{ get; set; }
        public contact ocontact { get; set;}         public contactSet(){
            ocontact = new contact();
            checked = false;
        }
        public contactSet(contact c){
            ocontact = c;
            checked = false;

        }
        public contactSet(contact c,string s){
            ocontact = c;
            checked = true;

        }
    }
   
 
}

getCurrentList populates the currentList in the page. refreshList2 will refresh the list when the link on top of the page to filter the contact is clicked.

This concept can be extended to multiple fields in the List .

 

Hierarchy in VisualForce

Hierarchy in VisualForce is an interesting feature unique to VisualForce

This is an example of how to build a hierarchy Lists in VF page with select checkboxes. It will have a checkbox at parent level with which you can select all the child automatically. It has a neat link with which you can show or hide children under a parent row. It uses jquery libraries for achieving this. It has a list of accounts with each accounts displaying all its contacts in a hierarchy view.

Apex Class

public class accconhierarchy {
    Private list acc;
   
    public List accountList { get; set; }
    public accconhierarchy (){
        List cw;
        accountList = new List();
        acc = [select id,name,industry,billingcountry,createdbyid,(select id,name,email,phone from contacts) from account limit 20];
        for(account a:acc){
            cw = new list();
            For(contact co : a.contacts){
               cw.add(new contactWrap(co));
            }
            accountList.add(new accountWrap(a,false,cw));
        }
    }
   
    public class accountWrap{
        public account oAccount{get;set;}
        public boolean isSelected{get;set;}
        public List contactset{get;set;}
        public accountWrap(account a,boolean b, List c){
            oAccount=a;
            isSelected=b;
            contactset =c;           
        }
    }
   
    public class contactWrap{
        public contact oContact{get;set;}
        public boolean isSelected{get;set;}       
        public contactWrap(contact a){
            oContact=a;
            isSelected=false;                      
        }
    }
   
}

Visualforce Page


 
     

 



                        rendered=”{!accountList.size!=0}”>


                           


                                   Action


                                   Account Name


                                   Industry


                                   Billing Country


                                   Createdby




                                value=”{!accountList}”
                                var=”item”>
                                  


                                    

                                            value=”{!item.IsSelected}”
                                            onclick=”javascript:toggleSelectAll(this, ‘{!$Component.repeatAccount}’);”/>
                                   


                                    
                                       
                                           
                                           


Contacts


                                               
                                                       Action
                                                       Name
                                                       Email
                                                       Phone

                                                    value=”{!item.contactSet}”
                                                    var=”subitem”>
                                                        

                       
                   
   
   
 

JS function toggleContactRow is used to show or hide contacts and toggleSelectAll is for header level checkbox at the parent Level.