[PrimeFaces] DataTable paging – set page programmatically with/without callback execution


Primefaces is a open source UI component library for JSF based application. One such component to show data in tables is datatable. Datatable has a lot of features like paging, sorting, selection, lazy loading etc.  Paging is a feature by which huge amount of data is displayed in pages. Some times there are cases to work with the page change event and also to set a page programmatically. Following is an extract from the stackoverflow answer to get the page change event using listener with the backing bean method handling the event:

<p:dataTable var="myVar" paginator="true" widgetVar="mydatatable" rows="1" value="#{myBean.listOfObjects}">
  <p:ajax event="page" update="buttons" listener="#{myBean.update}" oncomplete="setTimeout(function(){ alert("Page Change Completed"); }, 0);" />
  ...
  ...
</p:dataTable>
public void update(PageEvent event) {
  int var = event.getPage();
  ...
  ...
  ...
}

This works great, when the paging button is clicked the “update” method is called with the PageEvent object as argument, and using that object one can get a lot of info about the datatable like get the current page etc.

Now how about setting the page explicitly on the datatable in some other piece of backend code, Following are the 2 ways to set the page programmatically:

— set page by executing following client side code:

PF('widgetVar').getPaginator().setPage(pageindex);

this can be done in any backend Java code using the RequestContext’s execute method

RequestContext.getCurrentInstance().execute("PF('widgetVar').getPaginator().setPage(pageno)");

but be aware that when this method executes all the callbacks on the page event <p:ajax> element gets executed. Like in the above code “oncomplete” will be called and an alert with message will be shown.

— to avoid this callback to be called there is another way to set the page as shown below:

final DataTable d = (DataTable) FacesContext.getCurrentInstance().getViewRoot()
         .findComponent("myDataTable");
int first = 0;
d.setFirst(first);

remember that the “first” argument is the index of the of the row to be displayed and not the page number. The above code can be executed from any backend bean and the callbacks do not get executed.

Further Reading:

http://www.primefaces.org/

http://stackoverflow.com/questions/17543995/change-page-of-primefaces-datatable-with-pagination-from-commandlink

About Dominic

J for JAVA more about me : http://about.me/dominicdsouza
This entry was posted in Thechy Stuff and tagged , , , , , , , , . Bookmark the permalink.

Leave a comment