Reader small image

You're reading from  PrimeFaces Beginner's Guide

Product typeBook
Published inNov 2013
Reading LevelIntermediate
PublisherPackt
ISBN-139781783280698
Edition1st Edition
Languages
Right arrow
Author (1)
Siva Prasad Reddy Katamreddy
Siva Prasad Reddy Katamreddy
author image
Siva Prasad Reddy Katamreddy

K. Siva Prasad Reddy is a Senior Software Engineer living in Hyderabad, India, and having more than seven years of experience in developing enterprise applications with Java and JavaEE technologies. Siva is a Sun Certified Java Programmer and has a lot of experience in server-side technologies such as Java, JavaEE, Spring, Hibernate, MyBatis, JSF, PrimeFaces, and WebServices (SOAP/REST). Siva is also the author of Java Persistence with MyBatis 3, Packt Publishing. Siva normally shares the knowledge he has acquired on his blog at www.sivalabs.in. If you want to find out more about his work, you can follow him on Twitter (@sivalabs) and GitHub (https://github.com/sivaprasadreddy).
Read more about Siva Prasad Reddy Katamreddy

Right arrow

Chapter 8. Working with Data Components

PrimeFaces provides several data iteration components, which include DataList, DataTable, DataGrid, and so on. These can be used to display data in a tabular format. Also, PrimeFaces provides the DataExporter component to export data into PDF, Excel, CSV, or XML formats.

In this chapter we will cover:

  • Displaying data in a list layout using DataList

  • Displaying data in a tabular format using DataTable

  • Displaying data in a grid layout using the DataGrid component

  • Exporting data into PDF, XLS, CSV, and XML formats using DataExporter

Introducing the DataList component


The DataList component displays a collection of data in the list layout with several display types and supports AJAX pagination. The DataList component iterates through a collection of data and renders its child components for each item.

Let us see how to use <p:dataList> to display a list of tag names as an unordered list:

<p:dataList value="#{tagController.tags}" var="tag" type="unordered" itemType="disc">
  #{tag.label}
</p:dataList>

The preceding <p:dataList> component displays tag names as an unordered list of elements marked with disc type bullets. The valid type options are unordered, ordered, definition, and none.

We can use type="unordered" to display items as an unordered collection along with various itemType options such as disc, circle, and square. By default, type is set to unordered and itemType is set to disc.

We can set type="ordered" to display items as an ordered list with various itemType options such as decimal, A...

Time for action – displaying unordered and ordered data using DataList


Let us see how to display tag names as unordered and ordered lists with various itemType options.

  1. Create <p:dataList> components to display items as unordered and ordered lists using the following code:

    <h:form>
      <p:panel header="Unordered DataList">
    
        <h:panelGrid columns="3">
          <h:outputText value="Disc"/>
          <h:outputText value="Circle" />
          <h:outputText value="Square" />
    
          <p:dataList value="#{tagController.tags}" var="tag" itemType="disc">
            #{tag.label}
          </p:dataList>
          <p:dataList value="#{tagController.tags}" var="tag" itemType="circle">
            #{tag.label}
          </p:dataList>
          <p:dataList value="#{tagController.tags}" var="tag" itemType="square">
            #{tag.label}
          </p:dataList>
        </h:panelGrid>
      </p:panel>
    
      <p:panel header="Ordered DataList">
        <h:panelGrid...

Time for action – using DataList with pagination


Let us see how we can use the DataList component's pagination support to display five tags per page.

Create a DataList component with pagination support along with a custom paginatorTemplate:

<p:panel header="DataList Pagination">
  <p:dataList value="#{tagController.tags}" var="tag" id="tags" type="none"
    paginator="true" rows="5"
    paginatorTemplate="{CurrentPageReport} {FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink} {RowsPerPageDropdown}"
    rowsPerPageTemplate="5,10,15">
      <f:facet name="header">
        Tags
      </f:facet>
      <h:outputText value="#{tag.id} - #{tag.label}" style="margin-left:10px" />
      <br/>
  </p:dataList>
</p:panel>

What just happened?

We have created a DataList component along with pagination support by setting paginator="true". We have customized the paginator template to display additional information such as CurrentPageReport...

Displaying tabular data using the DataTable component


DataTable is an enhanced version of the standard DataTable that provides various additional features such as:

  • Pagination

  • Lazy loading

  • Sorting

  • Filtering

  • Row selection

  • Inline row/cell editing

  • Conditional styling

  • Expandable rows

  • Grouping and SubTable, and many more

In our TechBuzz application, the administrator can view a list of users and enable/disable user accounts. First, let us see how we can display a list of users using basic DataTable as follows:

<p:dataTable id="usersTbl" var="user" value="#{adminController.users}">
  <f:facet name="header">
    List of Users
  </f:facet>
  <p:column headerText="Id">
    <h:outputText value="#{user.id}" />
  </p:column>

  <p:column headerText="Email">
    <h:outputText value="#{user.emailId}" />
  </p:column>

  <p:column headerText="FirstName">
    <h:outputText value="#{user.firstName}" />
  </p:column>

  <p:column headerText="Disabled...

Time for action – using DataTable with pagination


Let us see how we can display five users per page using pagination.

Create a DataTable component using pagination to display five records per page, using the following code:

<p:dataTable id="usersTbl" var="user" value="#{adminController.users}" 
  paginator="true" rows="5"
  paginatorTemplate="{CurrentPageReport} {FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink} {RowsPerPageDropdown}"  
  currentPageReportTemplate="( {startRecord} - {endRecord}) of {totalRecords} Records."
  rowsPerPageTemplate="5,10,15"> 

  <p:column headerText="Id">  
    <h:outputText value="#{user.id}" />  
  </p:column>
  <p:column headerText="Email">
    <h:outputText value="#{user.emailId}" />
  </p:column>
  <p:column headerText="FirstName">
    <h:outputText value="#{user.firstName}" />
  </p:column>
  <p:column headerText="Disabled">
    <h:outputText value="#{user.disabled...

Time for action – using DataTable with filtering


Let us see how we can use filters with the users' DataTable.

  1. Create a DataTable component and apply column-level filters and a global filter to apply filters on all columns:

    <p:dataTable widgetVar="userTable" var="user" value="#{adminController.users}" 
        filteredValue="#{adminController.filteredUsers}" 
        emptyMessage="No Users found for the given Filters">  
      <f:facet name="header">  
        <p:outputPanel>  
          <h:outputText value="Search all Columns:" />  
          <p:inputText id="globalFilter" onkeyup="userTable.filter()" style="width:150px" />  
        </p:outputPanel>  
      </f:facet>
    
      <p:column headerText="Id">  
        <h:outputText value="#{user.id}" />
      </p:column>  
    
      <p:column headerText="Email" filterBy="#{user.emailId}" 
            footerText="contains" filterMatchMode="contains">
        <h:outputText value="#{user.emailId}" />
      </p:column>  
    
      <p:column...

Time for action – using DataTable with multiple row selection support


In this section we will demonstrate how to select multiple user rows and disable the selected users.

Create a DataTable component with the multiple row selection mode enabled, using the following code:

<p:dataTable var="user" value="#{adminController.users}"  
    selection="#{adminController.selectedUsers}" rowKey="#{user.id}">

  <p:column selectionMode="multiple"/>

  <p:column headerText="Id" width="20px;">  
    <h:outputText value="#{user.id}" />
  </p:column>  

  <p:column headerText="Email" >
    <h:outputText value="#{user.emailId}" />
  </p:column>  
  <f:facet name="footer">
    <p:commandButton value="Disable" actionListener="#{adminController.disableSelectedUsers}"/>
  </f:facet>
</p:dataTable>

What just happened?

We have created a DataTable component with multiple row selection support by using a nested <p:column> with selectionMode...

Time for action – using DataTable with row editing support


Let us see how to use the DataTable component row editing feature:

  1. Create a DataTable component with the editable mode enabled by setting editable to true:

    <p:dataTable id="usersTbl" var="user" value="#{adminController.users}" editable="true">  
      <p:ajax event="rowEdit" listener="#{adminController.onEdit}"/>  
      <p:ajax event="rowEditCancel" listener="#{adminController.onCancel}"/>
    
    <p:column headerText="Email">  
      <h:outputText value="#{user.emailId}" />  
    </p:column>
    
    <p:column headerText="FirstName">  
        <p:cellEditor>  
          <f:facet name="output">  
            <h:outputText value="#{user.firstName}" />  
          </f:facet>  
          <f:facet name="input">  
            <p:inputText value="#{user.firstName}"/>  
          </f:facet>  
        </p:cellEditor>
      </p:column>  
    
      <p:column headerText="Disabled">  
        <p:cellEditor>  
      ...

Time for action – using DataTable with cell editing support


Let us see how to use the cell editing feature of DataTable:

  1. Create a DataTable component with the editable mode enabled by setting editable to true and editMode to cell, as shown in the following code:

    <p:dataTable id="usersTbl" var="user" value="#{adminController.users}" editable="true" editMode="cell">  
      <p:ajax event="cellEdit" listener="#{adminController.onCellEdit}"/>
      <p:column headerText="FirstName">
        <p:cellEditor>
          <f:facet name="output">  
            <h:outputText value="#{user.firstName}" />  
          </f:facet>
          <f:facet name="input">  
            <p:inputText value="#{user.firstName}"/>
          </f:facet>
        </p:cellEditor>
      </p:column>
    </p:dataTable>
  2. Implement the cellEdit AJAX event listener method, onCellEdit():

    public void onCellEdit(CellEditEvent event)
    {
      Object oldValue = event.getOldValue();
      Object newValue = event.getNewValue...

Time for action – loading the DataTable data leisurely


Let us see how to use DataTable with the lazy loading feature.

  1. Create a DataTable component with the LazyDataModel binding and set the lazy attribute to true, as shown in the following code:

    <p:dataTable id="usersTbl" var="user" value="#{adminController.lazyUserModel}" paginator="true" rows="10" lazy="true"> 
      <p:column headerText="Id" sortBy="#{user.id}" >  
        <h:outputText value="#{user.id}" />  
      </p:column>  
    
      <p:column headerText="FirstName" filterBy="#{user.firstName}" sortBy="#{user.firstName}">  
        <h:outputText value="#{user.firstName}" />  
      </p:column>  
    </p:dataTable>
  2. Implement LazyUserModel by extending LazyDataModel to load data lazily:

    import org.primefaces.model.LazyDataModel;
    import org.primefaces.model.SortOrder;
    public class LazyUserModel extends LazyDataModel<User> 
    {
      public User getRowData(String rowKey) {  
            return loadUserFromDBByUserId(rowKey...

Displaying data in the grid layout using the DataGrid component


The DataGrid component can be used to display a collection of data in the grid layout along with pagination support.

Let us see how we can use the DataGrid component to display user details in a grid layout using pagination, displaying five users per page:

<p:dataGrid var="user" value="#{adminController.users}" 
      columns="3" rows="5" paginator="true"  
      rowsPerPageTemplate="5,10,15">  

  <p:panel header="#{user.firstName} #{user.lastName}" 
      style="text-align:center">  
    <h:panelGrid columns="1">  
      <h:outputText value="#{user.id} : #{user.emailId}" />  
    </h:panelGrid>  
  </p:panel>
</p:dataGrid>

The preceding code displays DataGrid as shown in the following screenshot:

As we have specified columns="3" and rows="5", DataGrid displayed five items arranged in three columns resulting in two rows. Here, rows represent the number of items to be displayed per page...

Exporting data into PDF/XLS/XML/CSV formats using the DataExporter component


The DataExporter component provides the ability to export the DataTable data into various formats such as Excel, PDF, CSV, and XML. DataExporter provides options for:

  • Exporting entire DataTable rows

  • Exporting only current page rows

  • Exporting only selected rows

  • Excluding particular columns

  • Customizing exporting data using pre- and post-processors

To export data into PDF and Excel formats, we need itext.jar and apache-poi.jar respectively to be added to the classpath:

<dependency>
  <groupId>org.apache.poi</groupId>
  <artifactId>poi</artifactId>
  <version>3.7</version>
</dependency>
<dependency>
  <groupId>com.lowagie</groupId>  <artifactId>itext</artifactId>
  <version>2.1.7</version>
</dependency>

The basic usage of DataExporter is as follows:

<p:dataTable id="usersTbl" var="user" value="#{adminController.users}">
  /...

Time for action – using DataExporter to export data into XLS and PDF formats


Let us see how we can use various features of DataExporter, such as exporting a whole dataset, exporting the only current page, and excluding some columns:

  1. Create a DataTable and a DataExporter component to export all the data, only page data, and register pre- and post-processors for XLS and PDF exporters:

    <p:dataTable id="usersTbl" var="user" value="#{adminController.users}" rowKey="#{user.id}"  paginator="true" rows="10">  
    
      <p:column headerText="Id"> 
        <f:facet name="header">  
          <h:outputText value="Id" />  
        </f:facet> 
        <h:outputText value="#{user.id}" />  
      </p:column>  
    
      <p:column>  
        <f:facet name="header">  
          <h:outputText value="Email" />  
        </f:facet>
        <h:outputText value="#{user.emailId}" />  
      </p:column>  
    
      <p:column exportable="false"> 
        <f:facet name="header">  
          <...

Summary


In this chapter, we have learned about data components, such as DataList and DataTable, along with various features, such as pagination, sorting, filtering, lazy loading, and so on. Also, we have seen how to use DataExporter for exporting data into PDF, Excel, CSV, and XML formats. In the next chapter, we will look into advanced data visualization components such as Carousel, Tree, TagCloud, and so on.

lock icon
The rest of the chapter is locked
You have been reading a chapter from
PrimeFaces Beginner's Guide
Published in: Nov 2013Publisher: PacktISBN-13: 9781783280698
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at £13.99/month. Cancel anytime

Author (1)

author image
Siva Prasad Reddy Katamreddy

K. Siva Prasad Reddy is a Senior Software Engineer living in Hyderabad, India, and having more than seven years of experience in developing enterprise applications with Java and JavaEE technologies. Siva is a Sun Certified Java Programmer and has a lot of experience in server-side technologies such as Java, JavaEE, Spring, Hibernate, MyBatis, JSF, PrimeFaces, and WebServices (SOAP/REST). Siva is also the author of Java Persistence with MyBatis 3, Packt Publishing. Siva normally shares the knowledge he has acquired on his blog at www.sivalabs.in. If you want to find out more about his work, you can follow him on Twitter (@sivalabs) and GitHub (https://github.com/sivaprasadreddy).
Read more about Siva Prasad Reddy Katamreddy