如何将 Primefaces 数据表从 bean 跳转到最后一页?

How to jump in Primefaces dataTable to last page from the bean?

我的 .xhtml 中有一个如下所示的数据表:

<p:dataTable var="category" value="#{beanView.categories}" paginator="true" rows="5" 
 paginatorTemplate="{RowsPerPageDropdown} {FirstPageLink} {PreviousPageLink} {CurrentPageReport} {NextPageLink} {LastPageLink}"
 rowsPerPageTemplate="5,10" id="categoryDT" styleClass="categoryClass"    
 editable="true" lazy="false" rowKey="#{category.id}">
 <!-- columns -->
<f:facet name="footer">
    <p:commandButton id="btnNewCat" 
      oncomplete="jQuery('.categoryClass').find('span.ui-icon-pencil').last().click();" 
    actionListener="#{beanView.onNewCategory}" 
    update="categoryDT" icon="ui-icon-plus" title="New Category" value="New Category" ></p:commandButton>
</f:facet></p:dataTable>

还有我的 bean beanView

public void onNewCategory(final ActionEvent actionEvent) {

    try {
        int rowCount = dataTable.getRowCount();
        int rowsPerPage = dataTable.getRows();
        int lastPage = rowCount / rowsPerPage;
        int rowFirst = (lastPage * rowsPerPage);

        if (rowCount >= rowsPerPage) {
            dataTable.setFirst(rowFirst);
            dataTable.setPageLinks(lastPage + 1);
            dataTable.setRowIndex(rowCount - 1);
        } else {
            ....
        }

        ....
     }
 }

但这实际上行不通!最后一页不会显示!

可以从 bean 单击我的数据表的最后一个页面按钮吗?或者有其他方法可以解决吗!

感谢您的帮助

您可以通过命令按钮的 oncomplete 来实现:

<p:commandButton oncomplete="PF('dataTableWV').paginator.setPage(PF('dataTableWV').paginator.cfg.pageCount - 1);"/>

或来自托管 bean:

RequestContext.getCurrentInstance().execute("PF('dataTableWV').paginator.setPage(PF('dataTableWV').paginator.cfg.pageCount - 1);");

注:dataTableWV为dataTable的widgetVar

我只是在补充 Hatem 的回答。

如果您需要检查仅在 adding/creating 成功后数据表中的一行并且没有发生验证错误时执行此操作,您可以使用:

action="#{myBean.createSelection}"
oncomplete="if ( !args.validationFailed &amp;&amp; args.created ) { PF('myDataTable').paginator.setPage(PF('myDataTable').paginator.cfg.pageCount - 1); }" />

oncomplete 方法具有参数 xhrstatusargs,控制器可以使用这些参数来 return 实际发生的事情。

在上面的例子中,我们将一些实体添加到数据表中,如果验证没有失败并且创建了一个新实体,我们只想翻页到最后一个实体,而不是在更新或删除时。

在你的控制器中,你can/should做:

    public void createSelection()
    {
        T selectedEntity = getSelectedEntity();
        
        T persistedEntity = null;
        
        try
        {
            persistedEntity = getEntityService().create( selectedEntity );
        }
        catch ( CreateException e )
        {
            ...

            return;
        }
        
        ...            
        
        PrimeFaces.current().ajax().addCallbackParam( "created", Boolean.TRUE );            
    }