user1423793 user1423793 - 1 month ago 5
Java Question

Sorting h:dataTable

I am using Seam and Java to make an h:dataTable that contains information from a ArrayList filled with objects. My question is, is there any way to sort the table by clicking on one of the headers. I have some code right now and all it does is reload the table the same way that it was.

Here's some of my code. Let me know if you need more:
Table:

<h:dataTable value="#{deliveryPort.getWholeDeliveryList()}" var="delivery" rules="rows">
<h:column>
<div class="setWidth">
<div class="white">
<f:facet name="header">
<h:outputLink style="color:#FFFFFF" action="#{deliveryPort.sortByAddress()}">
Address
</h:outputLink>
</f:facet>
</div>
<h:outputText value="#{delivery.address}" />
</div>
</h:column>


Sort:

public String sortByAddress(){
for(int i = 0; i < wholeDeliveryList.size(); i++){
for(int j= i+1; j<wholeDeliveryList.size(); j++){
if(wholeDeliveryList.get(i).getAddress().compareTo(wholeDeliveryList.get(j).getAddress())<1){
FlowerStoreDelivery temp = wholeDeliveryList.get(i);
wholeDeliveryList.set(i, wholeDeliveryList.get(j));
wholeDeliveryList.set(j, temp);
}
}
}
return "deliveryList.seam";
}


getWholeDeliveryList():

public List<FlowerStoreDelivery> getWholeDeliveryList(){
wholeDeliveryList = new ArrayList<FlowerStoreDelivery>();
wholeDeliveryList.addAll(entityManager.createQuery("SELECT e FROM FlowerStoreDelivery e").getResultList());
return wholeDeliveryList;
}

Answer

You can obtain a lot more info about DataTable including sorting and much more on this blog by BalusC, a JSF expert.