Tuesday, September 18, 2007

Sortable table using JSF and AJAX4JSF

I have written about AJAX and JSF in my previous post. Let us now look at a way to implement sortable tables using JSF and AJAX. We want to build a table which has the header as links. If a particular link is clicked, the table entries are sorted based on the header clicked. We want the entire functionality to be AJAX based, so that only part of the page is refreshed.

A normal JSF table looks like this:



<h:datatable id="addressTableHeader" border="0" cellpadding="0" cellspacing="0">
<h:column>
<f:facet name="header">
<h:outputtext value="Post Code">
</f:facet>
</h:column>
<h:column>
<f:facet name="header">
<h:outputtext value="Street">
</f:facet>
</h:column>
</h:dataTable>
<h:datatable id="addressTableBody" var="tableData" value="#{Bean.addressList}">
<h:column>
<h:outputtext value="#{tabledata.postcode}">
</h:column>
<h:column>
<h:outputtext value="#{tabledata.street}">
</h:column>
</h:dataTable>





The backing bean Bean.java has a method
getAddressList()
which wraps an ArrayList inside a ListDataModel and returns it.

We modify the table header from plain text to links which fire AJAX requests, using Ajax4JSF. We want the table body to be refreshed when the header is pressed, so we specify that in the reRender property of the commandLink.


<h:datatable id="addressTableHeader" border="0" cellpadding="0" cellspacing="0">
<h:column>
<f:facet name="header">
<a4j:commandlink action="#{Bean.postcodeSort}" ajaxsingle="true" rerender="addressTableBody" immediate="true">
<h:outputtext value="Post Code" styleclass="tariffpopupsearchheading">
</a4j:commandLink>
</f:facet>

</h:column>
<h:column>
<f:facet name="header">
<a4j:commandlink action="#{Bean.streetSort}" ajaxsingle="true" rerender="addressTableBody" immediate="true">
<h:outputtext value="Street" styleclass="tariffpopupsearchheading">
</a4j:commandLink>
</f:facet>
</h:column>
</h:dataTable>


We now add a Comparator to the back end code, which can help to sort the ArrayList of data to be presented in the table. The Comparator has different sorting criteria. New methods
postcodeSort()
and
streetSort()
are added to the Bean, which help to set the sorting criteria on click . The Bean's
getAddresslist()
method is modified to pass the appropriate Comparator.

Labels: , , ,

1 Comments:

Anonymous Anonymous said...

Thank you very much.
It's a good solution, which I search all working day.

10:26 PM  

Post a Comment

<< Home