Displaytag sort multiple columns
We had a need to sort by the main column selected and the user’s name. I wanted to keep using the internal sorting mechanism of displaytag rather than deal with callbacks to the controller to handle the sorting.
The current settings for the table are:
- sort=”list”
- defaultsort = col
- defaultorder =”ascending”
So, assume our table has two columns: name and year.
Sorting by name is easily accomplished: set sortProperty=”name”. Displaytag does this well.
The problem is year. We want to sort by year, but since there is liklihood of collision allow for name to be the secondary sort order.
In the dto used for the table elements we have the name and year fields. These are used as the displaytag property’s.
We can add an artificial accessor to the dto, call it YearName. We write an accessor for getYearName() which returns a new YearName object.
The YearName object has a constructor for YearName(year, name) that stuffs the other dto fields in it when called:
public class YearName {
private String year;
private String name;
public YearName(String year, String name) {
this.year = year;
this.name = name;
}
The YearName object also implements Comparator<YearName>. This comes down to a public int compareTo(YearName other).
In the compare routine we do something like:
public int compareTo(YearName other) {
int compare = this.year.compareTo(other.year);
if (compare!=0) return compare;
return this.name.compareTo(other.name);
}
So, with minor coding in the dto we keep using displaytag’s internal sorting mechanism.

Comments
Leave a comment Trackback