0

我正在使用 primefaces 的数据表组件来显示“学生”类的列表,类似于:

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">

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

4

1 回答 1

2

问题是仅当您单击排序图标时才会应用排序。作为一种解决方法,您可以调用数据表组件中的一些方法,首先知道最后“按列排序”是什么,然后您可以使用 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");
于 2013-05-28T14:38:23.133 回答