Reset page number on Primefaces “paginatable” component

Goal

To reset the page number of a component that presents its results in a paginated way

Description

Lets try this example:

  1. Use, e.g., a datatable that shows its results in a paginated way (use a datamodel to iterate the data) and that it is possible to filter results so that the number of results
  2. Make sure the results return more than one page and go to a page that is higher to the number of pages that will be returned in the next step
  3. Filter the results making sure that the number of pages returned will be lower than the page number where you wre

If you try that example, you may end up with a datatable showing no results unless you click two times on the filter button. This is because the datatable component’s paginator assumes it is still on the page as explained in the step 2 of the example before

How to

The fix is pretty simple, actually. All you need to do is to “reset” the page number of the paginator component on the filter button, as such (notice that this example is with Primefaces 3.5 – in Primefaces 5, for instance, accessing the “paginatable” component would be something like PF(‘componentName’).getPaginator() instead):

...
<h:form>
  <p:commandButton value="Filter" action="#{myBean.search}" 
    process="@form" update="@form" 
    onstart="myWidget.getPaginator().setPage(0)" />

  <p:dataList value="#{myBean.dataModel}" var="row" 
    paginator="true" rows="10" lazy="true" widgetVar="myWidget">
    ...
  </p:dataList>

</h:form>
...

Explanations

Accessing the widget’s paginator and setting the page to 0 (zero) makes sure the next search operation will make the data model’s load method present the first results, hence fixing the issue explained at the top of this recipe.

One comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s