Grids support the sorting of rows directly. To enable the ascending order for a particular column, you assign a java.util.Comparator instance to the sortAscending property of the column. Similarly, you assign a comparator to the sortDescending property to enable the descending order.
As illustrated below, you first implement a comparator that compares any two rows of the grid, and then assign its instances to the sortAscending and sortDescending properties. Notice: the compare method is called with two org.zkoss.zul.Row instance.
<zk> <zscript> class MyRowComparator implements Comparator { public MyRowComparator(boolean ascending) { ... } public int compare(Object o1, Object o2) { Row r1 = (Row)o1, r2 = (Row)o2; .... } } Comparator asc = new MyRowComparator(true); Comparator dsc = new MyRowComparator(false); </zscript> <grid> <columns> <column sortAscending="${asc}" sortDescending="${dsc}"/> ...
The sortDirection property controls whether to show an icon at the client to indicate the order of a particular column. If rows are sorted before adding to the grid, you shall set this property explicitly.
<column sortDirection="ascending"/>
Then, it is maintained automatically by grids as long as you assign the comparators to the corresponding column.
When you assign at least one comparator to a column, an onSort event is sent to the server if user clicks on it. The column component implements a listener to automatically sort rows based on the assigned comparator.
If you prefer to handle it manually, you can add your own listener to the column for the onSort event. To prevent the default listener to invoke the sort method, you have to call the stopPropagation method against the event being received. Alternatively, you can override the sort method, see below.
The sort method is the underlying implementation of the default onSort event listener. It is also useful if you wan to sort the rows by Java codes. For example, you might have to call this method after adding rows (assuming not in the proper order).
Row row = new Row(); row.setParent(rows); row.appendChild(...); ... if (!"natural".column.getSortDirection()) column.sort("ascending".equals(column.getSortDirection()));
The default sorting algorithm is quick-sort (by use of the sort method from the org.zkoss.zk.ui.Components class). You might override it with your own implementation.
Note: the sort method checks the sort direction (by calling getSortDirection). It sorts the rows only if the sort direction is different. To enforce the sorting, do as follows.
column.setSortDirection("natural"); sort(myorder);
The above codes are equivalent to the following.
sort(myorder, true);