Use Case
Sorting the wrapper class list to be displayed on visualforce
page on basis data from two fields.
Solution
We need to create different lists on the basis of data in one
field and then we need to sort those lists using compareTo implemented in
wrapper class. Finally adding those sorted lists in one list.
Apex Class:
Public
class MainController{
Public
List<WrapperClass> wrapperList {get;set};
public
String sortBy{get;set;}
public
String sortDir{get;set;}
Public class wrapperClass{
Public Boolean
IsVerified{get;set;}
Public String eName{get;set;}
Public Decimal marksObtained{get;set;}
Public String sortDir1 {get;set;}
Public String sortBy1 {get;set;}
Public wrapperClass(Boolean verify, String tmpName , Decimal marks){
this.IsVerified = verify;
this.eName = tmpName;
this.marksObtained = marks;
}
Public Integer compareTo(Object compareTo){
WrapperClass
wr = (WrapperClass)compareTo;
Integer returnValue = 0;
Integer
orderInd = sortDir1 == 'DESC' ? -1: 1;
if( sortBy1.equalsIgnoreCase('Name') ) {
returnValue = eName > wr.eName ? orderInd: (eName < wr.eName? orderInd*-1
: 0) ;
}else if( sortBy1.equalsIgnoreCase('marks') ){
returnValue = marksObtained > wr.marksObtained ? orderInd :
(marksObtained < wr.marksObtained ? orderInd*-1 : 0);
}
}
}
Public void setSorting(){
this.sortBy =ApexPages.currentPage().getParameters().get(SORT_BY);
this.sortDir=ApexPages.currentPage().getParameters().get(SORT_DIR);
List<WrapperClass> finalList = new List<WrapperClass>();
List<WrapperClass> verifiedList = new List<WrapperClass>();
List<WrapperClass> nonVerifiedList = new List<WrapperClass>();
for(WrapperClass
cl : wrapperList){
if(cl.Isverified){
verifiedlist.add(cl)
}
else
nonVerifiedList.add(cl);
}
for(WrapperClass li : verifiedlist){
li.sortBy1 = sortBy;
li.sortDir1 = sortDir;
}
verifiedlist.sort();
finalList.addAll(verifiedlist);
for(WrapperClass lis : nonVerifiedlist){
lis.sortBy1 = sortBy;
lis.sortDir1 = sortDir;
}
nonVerifiedlist.sort();
finalList.addAll(nonVerifiedlist);
wrapperList
= finalList;
}
}//Main
Class
Visualforce Page:
<apex:form
id="Form">
<apex:pageBlock
id="pageBlock" >
<table
id="myData">
<thead>
<tr>
<th title="Name"></th>
<th title="Marks Obtained">
<apex:commandLink action="{!setSorting}" value="marks"
reRender="DataPanel">
<img src="/s.gif"
class="sort{!if(sortDir=='ASC','Asc','Desc')}"
style="display:{!if(sortBy=='marks','','none')}" />
<apex:param value="marks" name="sortBy" />
<apex:param value="{!IF(sortBy='marks',IF(sortDir='ASC','DESC','ASC'),'ASC')}"
name="sortDir" />
</apex:commandLink>
</th>
<th title="Verified"></th>
</thead>
</table>
<apex:outputPanel id="DataPanel">
<table>
<apex:repeat value="{!wrapperList}" var="row">
<tr>
<td>{!row.Name}</td>
<td>{!row.marksObtained}</td>
<td>{!row.IsVerified}</td>
</tr>
</apex:repeat>
<table>
</apex:outputPanel>
</apex:pageBlock>
</apex:form>
No comments:
Post a Comment