How to sort in primefaces columns?

Alan Lanzoni picture Alan Lanzoni · May 14, 2014 · Viewed 7.8k times · Source

So, I've been trying for 3 days now... First, i've found that primefaces has a bug with the tag p:columns, as it's sortFunction asks for a property instead a method. So, i've found this solution: here Nevertheless, even reaching the method, i don't know what column i'm asking to sort, as I'm not sure if its possible to pass a parameter. Anyone can help? I'm using primefaces 5.0 here.

Here is my datatable:

<p:dataTable value="#{categoryBean.categories}" var="category">
    <p:column sortBy="#{category.name}">
        <f:facet name="header">
            <h:outputText value="Category"></h:outputText>
        </f:facet>
        <h:outputText value="#{category.name}"></h:outputText>
    </p:column>
    <p:columns value="#{categoryBean.columns}" var="column" columnIndexVar="i" sortBy="#{category}" sortFunction="#{categoryBean.customOrder}">
        <f:facet name="header">
            <h:outputText value="#{column.header}">
            </h:outputText>
        </f:facet>
        <h:outputText value="#{category[column.property][i].sumGrade/category[column.property][i].countGrade}"></h:outputText>
    </p:columns>
</p:dataTable>

And here are my methods:

public MethodExpression getCustomOrder() {
        FacesContext context = FacesContext.getCurrentInstance();
        return context.getApplication().getExpressionFactory()
            .createMethodExpression(context.getELContext(), 
            "#{categoryBean.customSort}", Integer.class, 
            new Class[] { Object.class, Object.class });
}


public int customSort(Object val1, Object val2) {
    System.out.println("mySort" + val1 + "/" + val2);
    return 0;
}

So, the object can reach the method, however, i need to know how to pass a parameter or something, so i can know which column i'm refering to. Thank you guys.

Answer

j.con picture j.con · May 14, 2014

<p:dataTable> has an attribute sortBy and sortOrder

for example

<p:dataTable id="table1" var="x" value="#{myBackingBean.myEntities}" sortBy="#{x.id}" sortOrder="descending">

...assuming your backing bean object has a .getId() field.