I have created a th/td HTML table where Wrapper class List is already sorted with Comparable interface.
Requirement – User should be able to sort it in descending order based on the same field as well as back to ascending order if required.
What would be the options for doing this change?
- A select list option with ascending/descending and calling method through ActionFunction?
- Anything like commandLink possible in HTML table where user clicks the label of the column to be sorted and they alternately sort as asc and desc?
- Any other suggestions ?
Updating code :
Obj To Compare method
public ProdWrapper(){
}
public ProdWrapper(Integer experienceNumberInt){
this.AccountNumber = AccountNumber ;
}
public Integer compareTo(Object ObjToCompare) {
ProdWrapper compareNum = (ProdWrapper)ObjToCompare;
if (AccountNumber > compareExpNum .AccountNumber ) {
return ascending ? 1 : -1;
} else if(AccountNumber < compareExpNum .AccountNumber ) {
return ascending ? -1 : 1;
} else {
return 0;
}
}
CommandLink
<th><apex:commandLink value="Account #" action="{!changeSort}" ><apex:param value="exp"/></apex:commandLink></th>
Best Answer
If you invert the sign of your Comparable, you'll get descending order. Depending on your exact requirements, this is usually pretty easy. Consider the following code:
I've left out some details, obviously, but this should point you in the right direction. Generally, I use apex:commandLink in the header cells to call changeSort, which takes care of all of the logic.
Edit: More Code
To sort by a column, just set the parameter for which field you wish to sort:
In the controller, there is a
public String sortField { get; set; }
andpublic Boolean sortAsc { get; set; }
; the former is set byapex:param
, the latter is used by theresort
method (above calledchangeSort
). This particular implementation uses a SOQL ORDER BY clause, but you can use dynamic SObject methods to use the Comparable interface.Also, see my answer on this question for how you could use an Interface to define which field is sorted (basically, you'd create a bunch of sorting interfaces, then select one to use). For example: