Sort wrapper class list in Apex

Sort wrapper list based on selected records.

Visualforce page:

 <apex:page showHeader="false" controller="WrapperListSortCntrl" >  
     <apex:slds />  
     <apex:form >  
       <div class="slds-page-header">  
          My Product  
       <table class="slds-table slds-table--bordered">  
             <th> Select</th>  
             <th> Name </th>  
             <th> Product Family </th>  
             <th> Description</th>  
             <th> Active</th>  
           <apex:repeat value="{!ProductList}" var="p">  
               <td><apex:inputcheckbox value="{!p.selectcheck }" styleClass="slds-checkbox"/></td>  

Apex Class:

 /* Name: WrapperListSortCntrl  
   Description: Wrapper List Sort  
   Created Date: 20/03/2019  
   LastModified Date: 20/03/2019  
   Created By: Arun Kumar  
 public class WrapperListSortCntrl{  
   public List<WrapperCls> ProductList{get;set;}  
   public WrapperListSortCntrl(){  
     ProductList = new List<WrapperCls>();  
   public void fetchProducts(){  
     for(Product2 p:[select id,Name,Family,Description,IsActive from Product2]){  
       Boolean check = false;  
         check = true;  
       ProductList.add( new WrapperCls(check, p));   
     system.debug('ProductList: '+ProductList);  
     ProductList.sort(); // this Wrapper list will be sort according to checkbox selected (isActive =true)  
   //Wrapper cls implements Comparable Interface  
   public class WrapperCls implements Comparable { //Adds sorting support for Lists that contain non-primitive types, that is, Lists of user-defined types.  
     public Boolean selectcheck {get;set;}    
     public Product2 prd{get;set;}    
     public WrapperCls(Boolean selectcheck, Product2 prd){  
       this.selectcheck = selectcheck ;  
       this.prd = prd;  
     public Integer compareTo(Object ObjectToCompare) { //Returns an Integer value that is the result of the comparison.  
       WrapperCls compareToWrapperCls = (WrapperCls)ObjectToCompare;  
       if (compareToWrapperCls.selectcheck )   
         return 1;  
         return 0;  


Comparable Interface:

Arun Kumar

Arun Kumar is a Salesforce Certified Platform Developer I with over 7+ years of experience working on the Salesforce platform. He specializes in developing custom applications, integrations, and reports to help customers streamline their business processes. Arun is passionate about helping businesses leverage the power of Salesforce to achieve their goals.

Leave a Reply