Sort wrapper list based on selected records.
Visualforce page:
<apex:page showHeader="false" controller="WrapperListSortCntrl" >
<html>
<head>
<apex:slds />
</head>
<body>
<apex:form >
My Product
<table class="slds-table slds-table--bordered">
<thead>
<tr>
<th> Select</th>
<th> Name </th>
<th> Product Family </th>
<th> Description</th>
<th> Active</th>
</tr>
</thead>
<tbody>
<apex:repeat value="{!ProductList}" var="p">
<tr>
<td><apex:inputcheckbox value="{!p.selectcheck }" styleClass="slds-checkbox"/></td>
<td>{!p.prd.Name}</td>
<td>{!p.prd.Family}</td>
<td>{!p.prd.Description}</td>
<td>{!p.prd.IsActive}</td>
</tr>
</apex:repeat>
</tbody>
</table>
</apex:form>
</body>
</html>
</apex:page>
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>();
system.debug('Insider');
fetchProducts();
}
public void fetchProducts(){
for(Product2 p:[select id,Name,Family,Description,IsActive from Product2]){
Boolean check = false;
if(p.isActive){
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;
else
return 0;
}
}
}
Reference:
Comparable Interface:https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_comparable.htm