Primefaces数据表排序顺序

时间:2013-05-13 08:37:00

标签: sorting primefaces datatable

我正在使用primefaces的数据表组件来显示类'Student'的列表,如下所示:

class Student {
    String firstName
    String lastName
    ....
}

我从原始查询填充列表。数据表组件如下:

<p:dataTable id="studentList" var="student" rowIndexVar="rowIndex"                          
    value="#{studentBean.studentList}"
    rowKey="#{student.firstName}" widgetVar="sList"
    sortBy="#{student.firstName}" sortOrder="ASCENDING">

我有一个基本上会刷新表中数据的按钮。问题是,当我刷新数据时,排序顺序全部丢失。如何保留排序顺序?

1 个答案:

答案 0 :(得分:2)

问题是排序仅在您单击排序图标时应用。作为一种解决方法,你可以调用datatable组件中的一些方法,首先要知道最后一个“按列排序”,你可以使用primefaces数据表排序功能。这将强制数据表随时进行排序:

/**
 * This code will first find what is the current order and the apply the sorting process to data.
 * It is implemented looking at primefaces code and doing exactly the same steps on sorting (like default database sort)
 *  and decide what is the current order (like in column rendering to decide what is the column arrow style).
 */
protected void refrestTableComponentOrder(DataTable table) {
    FacesContext facesContext = FacesContext.getCurrentInstance();
    //When view is not created, like on first call when preparing the model, table will not be found
    if(table == null){
        return;
    }
    ValueExpression tableSortByVe = table.getValueExpression("sortBy");
    String tableSortByExpression = tableSortByVe.getExpressionString();

    //Loop on children, that are the columns, to find the one whose order must be applied.
    for (UIComponent child : table.getChildren()) {
        Column column = (Column)child;
        ValueExpression columnSortByVe = column.getValueExpression("sortBy");
        if (columnSortByVe != null) {
            String columnSortByExpression = columnSortByVe.getExpressionString();

            if (tableSortByExpression != null && tableSortByExpression.equals(columnSortByExpression)) {
                //Now sort table content
                SortFeature sortFeature = new SortFeature();
                sortFeature.sort(facesContext, table, tableSortByVe, table.getVar(),
                    SortOrder.valueOf(table.getSortOrder().toUpperCase(Locale.ENGLISH)), table.getSortFunction());
                break;
            }
        }

    }
}

您可以通过以下方式在任何地方找到数据表组件:

FacesContext facesContext = FacesContext.getCurrentInstance();
DataTable table  = (DataTable)facesContext.getViewRoot().findComponent(":YOUR_TABLE_CLIENT_ID");