A blog about Salesforce CRM Configuration and development

Wednesday, 20 March 2019

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:https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_comparable.htm

1 comment:

Trailhead Profile

Follow by Email

Total Pageviews


Popular Posts

Powered by Blogger.

Contact form


Email *

Message *