Search code examples
jsfprimefacesprimefaces-datatable

Primefaces get name of sorted column


I need to get the name of the sorted/filtered column in my DataTable. With the ajax-event "filter" I get the filtered value and dthe column name. For the sorting I used the even "sort" but couldn't find the method which returns me the name of the sorted column

<p:dataTable id="userTable" var="user" value="#{userController.lazyModel}"
             widgetVar="userTableVar" selection="#{userController.selectedUser}" 
             paginator="true" rows="#{userController.defaultRows}" paginatorPosition="bottom" rowSelectMode="checkbox"
             lazy="true"
             paginatorTemplate="{RowsPerPageDropdown} {FirstPageLink} {PreviousPageLink} {PageLinks} {CurrentPageReport} {NextPageLink} {LastPageLink}"                                                             
             rowKey="#{user.userId}" rowsPerPageTemplate="#{userController.rowOptions}"
             emptyMessage="#{bundle.noRows}" >

    <p:ajax event="sort" listener="#{userController.onSort}"></p:ajax>
    <p:ajax event="filter" listener="#{userController.onFilter}"></p:ajax>

    <p:column selectionMode="multiple" style="width:16px;text-align:center"/>

    <p:column sortBy="#{user.username}"  filterBy="#{user.username}" style="width: 20%;" >
        <f:facet name="header" >
            <h:outputText value="Username"></h:outputText>
        </f:facet>
        <h:outputText value="#{user.username}"></h:outputText>
    </p:column>

    <p:column sortBy="#{user.userRight}"  filterBy="#{user.userRight}" style="width: 20%;" >
        <f:facet name="header" >
            <h:outputText value="Userright"></h:outputText>
        </f:facet>
        <h:outputText value="#{user.userRight}"></h:outputText>
    </p:column>


</p:dataTable>
public void onSort(SortEvent event) {
     System.out.println(event.isAscending() + " - "
                        + event.getSortColumnIndex() + " - "
                        + event.getSortColumn().getField());
}

public void onFilter(FilterEvent event) {
     System.out.println(event.getFilters());
}

Solution

  • You need to set the field attribute on the p:column.

    From the documentation:

    Name of the field to pass lazy load method for filtering and sorting. If not specified, filterBy / sortBy values are used to identify the field name.

    Then event.getSortColumn().getField() will work.