Reputation: 3595
I am using primefaces' datatable component to display a list of classes 'Student' which is something like :
class Student {
String firstName
String lastName
....
}
I populate the list form a native query. The datatable component is as follows :
<p:dataTable id="studentList" var="student" rowIndexVar="rowIndex"
value="#{studentBean.studentList}"
rowKey="#{student.firstName}" widgetVar="sList"
sortBy="#{student.firstName}" sortOrder="ASCENDING">
And I have a button which would basically refresh the data in the table. The problem is, when I refresh the data, the sorting order is all lost. How can I retain the sorting order?
Upvotes: 0
Views: 25017
Reputation: 96
The problem is that sorting is only applied just when you click the sorting icon. As a work around you can call some methods in datatable component to, first know what the last "sorted by column" and the you can use the primefaces datatable sorting feature. This will force the datatable to do the sorting whenever you want:
/**
* This code will first find what is the current order and the apply the sorting process to data.
* It is implemented looking at primefaces code and doing exactly the same steps on sorting (like default database sort)
* and decide what is the current order (like in column rendering to decide what is the column arrow style).
*/
protected void refrestTableComponentOrder(DataTable table) {
FacesContext facesContext = FacesContext.getCurrentInstance();
//When view is not created, like on first call when preparing the model, table will not be found
if(table == null){
return;
}
ValueExpression tableSortByVe = table.getValueExpression("sortBy");
String tableSortByExpression = tableSortByVe.getExpressionString();
//Loop on children, that are the columns, to find the one whose order must be applied.
for (UIComponent child : table.getChildren()) {
Column column = (Column)child;
ValueExpression columnSortByVe = column.getValueExpression("sortBy");
if (columnSortByVe != null) {
String columnSortByExpression = columnSortByVe.getExpressionString();
if (tableSortByExpression != null && tableSortByExpression.equals(columnSortByExpression)) {
//Now sort table content
SortFeature sortFeature = new SortFeature();
sortFeature.sort(facesContext, table, tableSortByVe, table.getVar(),
SortOrder.valueOf(table.getSortOrder().toUpperCase(Locale.ENGLISH)), table.getSortFunction());
break;
}
}
}
}
You can find the datatable component anywhere by calling:
FacesContext facesContext = FacesContext.getCurrentInstance();
DataTable table = (DataTable)facesContext.getViewRoot().findComponent(":YOUR_TABLE_CLIENT_ID");
Upvotes: 2