Martin Hampl
Martin Hampl

Reputation: 11

PrimeFaces datatable default sortBy from backing bean

I have a data table with a POJO object:

<p:dataTable id="table" var="object" sortBy="#{object.name}" sortOrder="DESCENDING">

object has fields id, name, date, size for example. I am able to set default sort field using xhtml, but I want set it from backing bean.

I am able to parse column id when user creates sort request for example name.

public void sortEventListener(AjaxBehaviorEvent actionEvent) {
    String id = ((SortEvent) actionEvent).getSortColumn().getColumnKey();
    String[] idPath = id.split(":");
    sortBy = idPath[idPath.length - 1];
    sortOrder = ((SortEvent) actionEvent).isAscending();
}

My task detects which column user wants to sort and persists it to db. After reload the data table should be sorted by this column.

When I set

sortBy="#{bean.sortBy}" // sortBy = name

it's not working and data table is not sorted after rendering the page.

Please help.

Upvotes: 1

Views: 5963

Answers (1)

Jasper de Vries
Jasper de Vries

Reputation: 20253

If you bind your data table to a org.primefaces.component.datatable.DataTable object in your bean or find the table component in your bean, you can use the table object to set the sortBy value expression programmatically.

To get an idea how PrimeFaces is handling sorting, you can have a look at the source code at GitHub.

When you have the sort column, you can easily get the sort value expression. So, in your listener you could use something like:

UIColumn sortColumn = sortEvent.getSortColumn();
ValueExpression sortByVE = sortColumn.getValueExpression("sortBy");

By the way, you can replace the parameter type AjaxBehaviorEvent with SortEvent in your sort listener method.

Now, store the sortByVE expression, and set it as the sortBy value expression of the bound table when needed:

dataTable.setValueExpression("sortBy", sortByVE);

If you want to create the value expression from scratch, use something like:

FacesContext context = FacesContext.getCurrentInstance();
ExpressionFactory ef = context.getApplication().getExpressionFactory();
ValueExpression ve = ef.createValueExpression(context.getELContext(),
                                              "#{object.name}",
                                              Object.class);
dataTable.setValueExpression("sortBy", ve);

In this example "#{object.name}" is fixed. You should construct it based on the value you get from your sort listener.

If you want to find your table in your bean, OmniFaces Components might be helpful. It also offers a shortcut method to create value expressions.

See also:

Upvotes: 4

Related Questions