Sorting is not working in datatable in PrimeFaces. Please suggest.
See below my .xhtml file
I had a problem sorting when my backing bean was sessionScoped. Not sure what your exact problem is, but if you hit the sort button and nothing happens, try changing your scope to @ViewScoped.
If you populate your table in the getter sorting wont work (as described above). You should put in your getter like:
public List<Row> getTableData() {
if (tableDataList == null)
tableDataList = dao.getTableData();
return tableDataList;
}
You can then reset(refresh) your "cash" by punting tableDataList = null; if you wont your datatabele refreshed.
have you tried @SessionScoped? it works fine to me, hope this help.
I don't know if it's your case. There's a primefaces issue. A bug on sort of datatable. Take a look here: https://code.google.com/archive/p/primefaces/issues/2476
There are some workarounds:
you can use a lazyDataModel for your datatable, it works.
you can force the sort order.
In your datatable catch the sort event
<p:dataTable style="width: 60%" id="dt1" value="#{bean.list}" var="entry" first="0" paginator="true" rows="10" paginatorTemplate="{CurrentPageReport} {FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink} {RowsPerPageDropdown}" rowsPerPageTemplate="5,10,15" emptyMessage="No cars found with given criteria" >
<p:ajax event="sort" listener="#bean.sortListener}" />
In your managed bean you set a order by string to add to your query
private String orderBy = "";
public void sortListener(SortEvent event) {
String orderColumn = event.getSortColumn().getValueExpression("sortBy").getExpressionString();
//you will get the content of the attribute SortBy of the column you clicked on, like #{entry.carno}
orderColumn = orderColumn.replace("#{entry.", "");
orderColumn = orderColumn.replace("}", "");
orderBy = " order by " + orderColumn + (event.isAscending()? " asc " : " desc ");
}
public List<Car> getList(){
String query = "[...your query...]" + orderBy;
...[execute your query and get your ordered list]
}
The primefaces backing bean (ViewScoped!) must hold it's own List of rows. So, e.g., if you query the database every time you request the p:dataTable:value
, sorting will not work.
Solution: Collect the List from the Database and keep it in a local List variable in the backing bean.
public List<Row> getDataTable() {
if (tableDataList == null)
tableDataList = loadListOnce();
return tableDataList;
}
The Problem is:
<f:event type="preRenderView" listener="#{MyBackingBean.load}"></f:event>
Sorting is done by the <p:dataTable/>
at PhaseId.APPLY_REQUEST_VALUES
on the list, with the <f:event type"preRenderView"/>
you reload the list at PhaseId.RENDER_RESPONSE
and so you lost the sorting.
Solution: use <f:event type="postAddToView"/>
<f:event type="postAddToView" listener="#{MyBackingBean.load}" />
This will reload the list at PhaseId.RESTORE_VIEW before sorting is done by <p:dataTable/>
.
Tested with PrimeFaces Version 3.1.1 and Mojarra 2.1.8