Friday, January 11, 2013

JSF 2.x Tip of the Day: RichFaces Table Sorting (3-position switch design)

A technique I like to call the three position switch is what I use for sorting on my RichFaces tables. This consists of default (unsorted), ascending, and descending. It is implemented very easily by setting the <rich:column/> sortOrder attribute to point to our current sort, and using an <a4j:commandLink> in the header facet to control the sort as shown in the example below. This simple technique makes sorting simple and sexy.

code

1
2
3
4
5
6
<rich:column sortBy="#{customer.name}" sortOrder="#{complexDataTable.sorting}">
    <f:facet name="header">
        <a4j:commandLink render="dataTable" value="#{complexDataTable.customerColumnHeader}" action="#{complexDataTable.sort()}"/>
    </f:facet>
    <h:outputText value="#{customer.name}"/>
</rich:column>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
private SortOrder sorting = SortOrder.unsorted;
 
public SortOrder getSorting() {
    return sorting;
}
 
public void setSorting(SortOrder sorting) {
    this.sorting = sorting;
}
 
public void sort() {
    switch (sorting) {
        case unsorted: {
            sorting = SortOrder.ascending;
            break;
        }
        case ascending: {
            sorting = SortOrder.descending;
            break;
        }
        case descending: {
            sorting = SortOrder.unsorted;
            break;
        }
    }
}

This additional code will let the user know which sorting direction we are currently using.
1
2
3
4
5
6
7
8
9
10
public String getCustomerColumnHeader() {
    switch (sorting) {
        case unsorted: {
            return "Customer Name";
        }
        default: {
            return "Customer Name (" + sorting + ")";
        }
    }
}

3 comments :

dShringi said...

You need to remove brackets from sort method:
action="#{complexDataTable.sort}"

dShringi said...

There is a syntactical error in action="#{complexDataTable.sort()}" you need to remove brackets.

John Yeary said...

That is not correct!

I tested it on GlassFish 3.0.1, 3.1, 3.1.1, 3.1.2, and 3.1.2.2 and it worked perfectly fine. I checked it after you posted your comment. It was developed on GlassFish 3.1.2.2.

Popular Posts