devsnd
devsnd

Reputation: 7722

Adding sortBy attribute programatically to primefaces DataTable Column

I'm trying to put the sortBy attribute into the primefaces datatable Column programatically. I have inherited from DataTable, and creating my own Columns using a custom getColumns() call.

Unfortunately there seems to be no clean way to insert the sortBy attribute to the column, since the method yet doesn't know the context it is in.

public List<Column> getColumns() {
    if (columns == null) {
        columns = new ArrayList<Column>();
        String[] columnStrings = getShowColumns().split(",");
        for (String columnString : columnStrings) {
            Column column = getColumnByType(columnString.trim());
            if (column != null) {
                //here I have to add the sortBy Expression somehow,
                //but there is no context to construct it from
                //column.setSortBy(ValueExpression)
                columns.add(column);
            }
        }
    }
    return columns;
}

It seems obvious to me, that I am missing something, but I am lost rightnow. The Column seems to be filled with that ValueExpression somewhere else, but I can't find out where...

I tried to go through all the code using the debugger, but I can't figure out when the ValueExpression is generated in the original implementation. Any hints appreciated.

Upvotes: 1

Views: 4692

Answers (1)

Fallup
Fallup

Reputation: 2427

ValueExpression for sortBy is not stored anywhere if the column doesn't have sortBy specified, which is your case. You have to create your own ValueExpression for each column which should be sortable.

I assume you know the column type and value so you can try this:

Column column = getColumnByType(columnString.trim());
FacesContext facesContext = FacesContext.getCurrentInstance();
ELContext elContext = facesContext.getELContext();
ExpressionFactory elFactory = facesContext.getApplication().getExpressionFactory();
ValueExpression valueExpresion = elFactory.createValueExpression(elContext, column.getValue(), column.getType());

Else if you don't know the type and value :

 String valueExprs = "#{data.street}"; // for example
    ...
    Column column = getColumnByType(columnString.trim());
    ...
    FacesContext facesContext = FacesContext.getCurrentInstance();
    ELContext elContext = facesContext.getELContext();
    ExpressionFactory elFactory = facesContext.getApplication().getExpressionFactory();
    ValueExpression valueExpression = elFactory.createValueExpression( elContext, valueExprs, String.class);

And now you can set sortBy :

column.setValueExpression("sortBy", valueExpression);

Notice using column.setValueExpression instead of column.setSortBy - it causes less troubles and work most of the time.

Hope it helped !

Upvotes: 4

Related Questions