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 3. Using PrimeFaces Common Utility Components

Most of the web applications need some common features such as displaying alerts, confirmation dialogs, error messages, tooltips and so on. JavaScript provides many of these features but those features are basic and limited. PrimeFaces provides some utility components such as Dialog, Tooltip, Growl, BlockUI and so on, that are commonly used with enhanced features and theming capabilities.

In this chapter we will cover the following topics:

  • Displaying FacesMessages using Message, Messages, and Growl

  • Displaying tooltips using the Tooltip component

  • Partial Processing and Rendering using the Fragment component

  • Introducing the Sticky component

  • Using the RequestContext Utility

  • Using the Dialog and ConfirmDialog components

  • Displaying notification messages using NotificationBar

  • Blocking UI components using BlockUI

  • Working with the PrimeFaces Selectors API

  • Introducing the search expression framework

Introducing the Message component


Message is an enhanced version of the standard JSF Message component with additional features and skinning capabilities. The <p:message> component is similar to the standard JSF's <h:message>, and is used to output a single message for a specific component as follows:

<p:message for="email"/>

The <p:message/> component provides the following attributes, which can be used to customize message display:

  • showSummary: This specifies whether the summary of FacesMessages should be displayed. Default value is false

  • showDetail: This specifies whether the detail of FacesMessages should be displayed. Default value is true

  • for: ID of the component whose message is to be displayed

  • display: Display mode can be text, icon, or both. Default is both.

    • text: Only message text is displayed

    • icon: Only message severity is displayed and message text is visible as a tooltip

    • both: Both icon and text are displayed

  • escape: This defines whether HTML would be escaped or...

Time for action – displaying FacesMessage using <p:message>


Let us see how to display FacesMessages with different display modes and severity levels.

  1. Create a form with three required input fields and display validation errors using <p:message> as follows:

    <h:form id="userRegForm" style="width: 500px; padding-left: 10px;">
      <p:panel header="Messages - Using 'display' modes" >
        <h:panelGrid columns="3">
          <p:outputLabel value="EmailId"/>
          <p:inputText id="emailId" value="#{messagesController.user.emailId}" required="true" requiredMessage="Enter EmailId"/>
          <p:message for="emailId"/>
          
          <h:outputText value="Password" />
          <p:password id="password" value="#{messagesController.user.password}" required="true" requiredMessage="Enter Password"/>
          <p:message  for="password" display="text"/>
          
          <h:outputText value="FirstName" />
          <p:inputText id="firstName" value="#{messagesController...

Time for action – displaying FacesMessage with HTML content


Let us see how to use the escape attribute, while displaying FacesMessages with HTML content. Perform the following steps:

  1. Create a form with two input fields as follows:

    <h:form id="form1" style="width: 500px; padding-left: 10px;">
      <p:panel header="Messages with HTML content - Using 'escape' attribute">
      <h:panelGrid columns="3">
        <h:outputText value="FirstName" />
        <p:inputText id="fName" value="#{messagesController.user.firstName}"/> 
        <p:message for="fName" escape="false" />
        
        <h:outputText value="LastName" />
        <p:inputText id="lName" value="#{messagesController.user.lastName}"/> 
        <p:message for="lName" escape="true" />
        
        <p:commandButton value="Submit" actionListener="#{messagesController.addHtmlMessages}" update="form1"/>
      </h:panelGrid>
      </p:panel>
    </h:form>
  2. In action Handler method, addHtmlMessages(), add FacesMessage...

Introducing the Messages component


The Messages component <p:messages> is an enhanced version of the standard JSF <h:messages> component with skinning capabilities. The <p:messages> component can be used to display multiple messages corresponding to UI elements.

The <p:messages/> component supports the following additional attributes in addition to the attributes supported by <p:message>:

  • globalOnly: When true, only FacesMessage with no clientIds are displayed. Default value is false.

  • autoUpdate: This enables the autoupdate mode if set to TRUE. Default value is false.

  • for: This specifies the name of associated key, takes precedence when used with globalOnly.

  • closable: This adds a close icon to hide the messages.

Time for action – displaying FacesMessage using <p:messages>


Let us see how to display multiple FacesMessage using <p:messages>:

  1. Create a form with two commandButton elements and the <p:messages/> component using the following code:

    <h:form style="width: 500px; padding-left: 10px;">
      <p:panel header="Messages with All Severity levels">
      <p:messages globalOnly="true" autoUpdate="true"/>
      <p:commandButton value="Show FacesMessages" actionListener="#{messagesController.addMultipleMsgs}"/>
      </p:panel>
    </h:form>
  2. Add FacesMessage in the actionListener method as follows:

    public void addMultipleMsgs()
    {
      FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO,"Sample Info Msg", null));
      FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN,"Sample Warn Msg", null));
      FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR...

Displaying notifications using the growl component


The PrimeFaces Growl component is similar to MAC OS's growl notification widget, which can be used to display FacesMessage. The Growl component is similar to the Messages component, and thus have similar attributes to customize its behavior.

We can use the following attributes to customize the Growl components behavior:

  • autoUpdate: When enabled, growl is updated for each AJAX request implicitly.

  • severity: It is a comma-separated list of severity levels for display purposes only.

  • globalOnly: When true, only the FacesMessage without client IDs are displayed. Default is false.

  • sticky: It specifies whether the message should stay instead of being hidden automatically. Default is false.

  • life: It is the duration in milliseconds to display non-sticky messages. Default is 6000 ms.

  • for: Identifier of the component whose messages to display only, takes precedence when used with globalOnly.

  • escape: It defines whether HTML would be escaped or not, defaults...

Time for action – displaying FacesMessages with growl


We will see how to display FacesMessages with different severity levels as Growl notifications using <p:growl>. Perform the following steps:

  1. Create a JSF page with a form and growl component:

    <p:growl id="growl1" autoUpdate="true" severity="info,warn,error, fatal" sticky="true" globalOnly="true"/>
    <h:form>
      <p:commandButton actionListener="#{messagesController.addMultipleMsgs}" value="Add Multiple Messages"/>
    </h:form>

What just happened?

When the button is clicked, we have added FacesMessages. The growl component gets updated automatically and displayed notifications because we have set autoUpdate mode to true.

Displaying tooltips using the Tooltip component


Browsers provide native support for showing tooltips using the title attribute, but it is too primitive. PrimeFaces provides a Tooltip component with enhanced features and various customization options such as effects, events and custom content support.

By default, tooltips will be displayed on the mouseover event and hides on the mouseout event. We can customize this behavior using the showEvent and hideEvent attributes:

<p:tooltip for="emailId" showEvent="focus" hideEvent="blur" value="Please enter Email Id (Ex: admin@gmail.com)"/>

We can also specify tooltip text using the title attribute on the component itself:

<p:inputText id="emailId" value="" title="Please enter Email Id (Ex: admin@gmail.com)"/>
<p:tooltip for="emailId" showEvent="focus" hideEvent="blur" />

We can apply different styles of effects while showing or hiding tooltips using the showEffect and hideEffect attributes:

<p:tooltip for="emailId" showEffect="slide...

Time for action – displaying tooltip for UI components


Let us see how to display tooltips on various events, with different effects and containing HTML elements, such as images, by performing the following steps:

  1. Create a form with input fields and add a <p:tooltip> component to display the tooltip using the following code:

    <h:form title="Tooltip demo form">
      <p:panel header="Form with Tooltips">
      
        <h:panelGrid columns="3">
          <p:outputLabel value="EmailId:"/>
          <p:inputText id="emailId" value=""/>
          <p:tooltip for="emailId" value="Please enter Email Id (Ex: admin@gmail.com)"/>
          
          <p:outputLabel value="FirstName:"/>
          <p:inputText id="firstName" value=""/>
          <p:tooltip for="firstName" showEvent="focus" hideEvent="blur" value="Please enter FirstName"/>
          
          <p:outputLabel value="LastName:"/>
          <p:inputText id="lastName" value=""/>
          <p:tooltip for="lastName" showEffect...

Time for action – using global tooltips


Let us see how we can use global tooltips to display tooltips for all the components, which are specifying the title attribute. Perform the following steps:

  1. Include a global Tooltip component and specify tooltips for various components using the title attribute as follows:

    <p:tooltip />
    <h:form>
        <h:panelGrid id="grid" columns="2" cellpadding="5">
            <h:outputText value="Input: " />
            <p:inputText id="focus" title="Tooltip for an input"/>
    
            <h:outputText value="Link: " />
            <h:outputLink id="fade" value="#" title="Tooltip for a link">
                <h:outputText value="Fade Effect" />
            </h:outputLink>
    
            <h:outputText value="Button: " />
            <p:commandButton value="Update" title="Update Components" update="@parent"/>
        </h:panelGrid>
    </h:form>

What just happened?

We have used a global <p:tooltip/> component to display tooltips...

Partial Processing and Rendering using the Fragment component


The Fragment component can be used to define a segment of components that should be partially processed, and updated when an AJAX request is triggered by any descendant component. This comes in very handy when there are multiple sections of the form with different actions for each segment.

By using fragments, Partial Processing and Rendering becomes very easy because we don't need to specify the component IDs to be processed using the process attribute, and component IDs to be updated using the update attribute.

For example, in the User Account screen we can have User Details and Contact Details sections, each with a command button to update the respective sections' fields.

Time for action – using the Fragment component


Let us look at how we can use two fragments for the User Details and Contact Details sections and partially process each of them individually. Perform the following steps for using two fragment components:

  1. Create a form with two fragments for User Details and Contact Details sections as follows:

    <h:form>
      <p:panel header="User Account>
      <p:fragment autoUpdate="true"> 
      <p:fieldset legend="User Details"> 
      <h:panelGrid columns="3">  
         <h:outputLabel for="emailId" value="EmailId:" />  
        <p:inputText id="emailId" value="#{userController.emailId}" required="true" label="emailId"/>
        <p:message for="emailId" display="icon"/>
          
        <h:outputLabel for="firstName" value="FirstName:" />
        <p:inputText id="firstName" value="#{userController.firstName}" required="true" label="FirstName"/>
        <p:message for="firstName" display="icon"/>
          
        <h:outputLabel for=...

Introducing the Sticky component


Sticky component can be used to make other components stick within the viewport while scrolling. For example, we may want to stick the top header and navigation menu bar section of the web page while scrolling.

Let us see how we can make the header and menu bar sticky with a <p:sticky> component using the following code:

<h:body>       
  <div class="wrapper">
  <p:panel id="headerSection">
  <p:panel id="header"  style="height: 80px; margin-bottom: 2px;">
    <h1>TechBuzz</h1>
  </p:panel>
  <h:form id="mainMenuForm">
     <p:menubar>
    <p:menuitem value="Home" url="home.jsf"/>
    <p:menuitem value="New Post" url="createPost.jsf"/>
    <p:menuitem value="Search" url="search.jsf"/>
    <p:menuitem value="My Account" url="userAccount.jsf"/><p:menuitem value="Administration" url="admin.jsf"/>
     </p:menubar>
  </h:form>
  </p:panel>
  <p:panel style...

Introducing the RequestContext utility


RequestContext is a utility class provided by PrimeFaces with the following features, which come in handy at times:

  • Update UI components from Managed Bean methods programmatically

  • Execute JavaScript from Managed Bean methods

  • Add AJAX callback parameters

  • ScrollTo a specific component after the AJAX update

The RequestContext utility class can be used with both AJAX and Non-AJAX requests. We can also use the requestContext.isAjaxRequest() method to determine whether the current request is an AJAX or Non-AJAX request.

Updating UI components

Normally we use the update attribute to specify the component ID(s) that needs to be updated after an AJAX request is completed.

We can also update the components using the org.primefaces.context.RequestContext utility function.

Time for action – updating UI components using RequestContext.update()


In this section, we will demonstrate how to update client-side view components from the server side using the following steps:

  1. Create a form with an input field and a submit button as follows:

    <h:form id="form1">
      <h:panelGrid columns="2">
        <h:outputLabel value="EmailId" />
        <p:inputText id="emailId" value="#{requestContextController.emailId}"/>
        
        <p:commandButton id="submitBtn" value="Submit" actionListener="#{requestContextController.handleSubmit}" />
      </h:panelGrid>
      <h:outputText value="You have Entered : #{requestContextController.emailId}" />
    </h:form>
  2. In the action handler method, update the form component using the RequestContext.update() method as follows:

    public void handleSubmit(ActionEvent ae)
    {
      RequestContext.getCurrentInstance().update("form1");
    }

What just happened?

We got a RequestContext instance using RequestContext.getCurrentInstance() and...

Time for action – executing JavaScript using RequestContext.execute()


We will now take a look at how to execute client-side JavaScript code from server-side code by performing the following steps:

  1. Create a form with a Dialog component using the following code:

    <h:form id="form1">
      <h:panelGrid columns="2">
        <h:outputLabel value="EmailId" />
        <p:inputText id="emailId" value="#{requestContextController.emailId}"/>
        
        <p:commandButton id="submitBtn" value="Submit" actionListener="#{requestContextController.handleSubmit}" />
      </h:panelGrid>
    
      <p:dialog header="Information" widgetVar="dlg" closeOnEscape="true" modal="true">
        You have Entered : #{requestContextController.emailId}
      </p:dialog>
    </h:form>
  2. In the action handler method, execute the JavaScript call, dlg.show(), to display a dialog widget using the RequestContext.execute() method. Use the following code for the same:

    public void handleSubmit(ActionEvent ae)
    {
      RequestContext...

Time for action – adding callback parameters using RequestContext.addCallbackParam()


In this section, we will see how to add callback parameters to an AJAX response payload by performing the following steps:

  1. Create a form with an input field and submit button using the following code:

    <h:form id="form1">
      <h:panelGrid columns="2">
        <h:outputLabel value="EmailId" />
        <p:inputText id="emailId" value="#{requestContextController.emailId}" required="true"/>
        
        <p:commandButton id="submitBtn" value="Submit" actionListener="#{requestContextController.handleSubmit}" 
        oncomplete="handleComplete(xhr, status, args)"/>
      </h:panelGrid>
      <h:outputText value="You have Entered : #{requestContextController.emailId}" />
    
    </h:form>
  2. Implement the oncomplete callback JavaScript function handleComplete() as follows:

    <script type="text/javascript">  
      function handleComplete(xhr, status, args) 
      {  
        if(args.validationFailed) {
          alert...

Displaying pop-up dialogs using the Dialog component


Dialog is a container component that can contain other components, and overlay other elements on the page. By default, the Dialog component will not be visible. We can use a client-side API to show or hide the dialog.

Time for action – displaying a dialog


Let us see how to create a basic Dialog component and show/hide based on button click events by performing the following steps:

  1. Create a form with a Dialog component and two buttons to show and hide the dialog using the following code:

    <h:form>
      <p:commandButton value="ShowDialog" onclick="dlg1.show();" type="button" />
      <p:commandButton value="HideDialog" onclick="dlg1.hide();" type="button" />
      <p:dialog id="simpleDialog" header="Simple Dialog" widgetVar="dlg1" width="300" height="50">
        <h:outputText value="PrimeFaces Simple Dialog" />
      </p:dialog>
    </h:form>

What just happened?

We have created a Dialog component using <p:dialog> and used two <p:commandButton> components to perform show and hide actions on the dialog box using client-side API calls dlg1.show() and dlg1.hide().

The Dialog component has the following attributes, which can be used to customize its behavior:

  • widgetVar: This specifies...

Time for action – client-side callbacks for onShow and onHide


Here we will demonstrate how to trigger JavaScript functions when dialog show and hide events happen. Perform the following steps:

  1. Create a Dialog component and two JavaScript functions to be called as callback functions for onShow and onHide events:

    <h:head>
      <script>
        function simpleDlgOnShowCallback()
        {
          alert('Simple Dialog displayed successfully');
        }
    
        function simpleDlgOnHideCallback()
        {
          alert('Simple Dialog is closed successfully');
        }
        
      </script>
    </h:head>
    
      
    <h:form>
      
      <p:commandButton value="ShowDialog" onclick="dlg1.show();" type="button" />
      <p:commandButton value="HideDialog" onclick="dlg1.hide();" type="button" />
      
      <p:dialog id="simpleDialog" header="Simple Dialog" widgetVar="dlg1" width="300" height="50"
            onShow="simpleDlgOnShowCallback()" onHide="simpleDlgOnHideCallback()">
        <h:outputText value="PrimeFaces...

Time for action – the Dialog component close event listener


Let us see how we can register a listener for the close event using the following steps:

  1. Create a Dialog component and register a close event listener using the <p:ajax> tag:

    <h:form id="form3" style="width: 400px;">
      <p:messages id="msgs" for="SampleDialog"/>
      <p:panel header="Dialog - Close Event Listener">
        <p:commandButton value="ShowDialog" onclick="dlg3.show();" type="button" /> 
        
        <p:dialog id="SampleDialog" header="Sample Dialog" widgetVar="dlg3" width="300" height="50" 
              showEffect="bounce"  hideEffect="explode" closeOnEscape="true">
          <p:ajax event="close" update="msgs" listener="#{dialogController.handleDialogClose}"/>
          <p:outputLabel value="PrimeFaces Dialog"/> 
        </p:dialog>
      </p:panel>
    </h:form>
  2. Implement the handleDialogClose() method to handle the close event:

    public void handleDialogClose(CloseEvent event) 
    {  
      String...

Time for action – creating dialog with a registration form


In this section, we will demonstrate how to use forms in Dialog components and close the dialog conditionally such as in a successful form submission.

  1. Create a dialog containing a user Registration Form using the following code:

    <p:messages id="globalMsgs" globalOnly="true" autoUpdate="true"/>
    <h:outputLink id="registerLink" value="javascript:void(0)" onclick="registrationDlg.show()" title="Registration">
      <p:outputLabel value="Register"/>  
    </h:outputLink>
    
    <p:dialog id="registrationDlgId" widgetVar="registrationDlg" header="Registration Form" focus="registrationFormDlg:firstName">
      
      <h:form id="registrationFormDlg">
        <p:messages id="regmsgs" severity="error"/>
        <h:panelGrid columns="2" width="400px">
          <p:outputLabel value="EmailId:"/>
          <p:inputText value="#{dialogController.registerUser.emailId}" required="true" label="EmailId"/>
          
          <p:outputLabel...

Introducing dialog framework


PrimeFaces 4.0 introduces a new dialog framework, which can be used to generate dynamic dialog components at runtime with the content from any external facelets page.

In order to use a dialog framework, first we need to configure DialogActionListener, DialogNavigationHandler, and DialogViewHandler in faces-config.xml as follows:

<faces-config ...>
  <application>
    <action-listener>
    org.primefaces.application.DialogActionListener
  </action-listener>
    <navigation-handler>
    org.primefaces.application.DialogNavigationHandler
  </navigation-handler>
    <view-handler>
    org.primefaces.application.DialogViewHandler
  </view-handler>
  </application>
</faces-config>

We can use the RequestContext.openDialog() and RequestContext.closeDialog() methods to open and close the dialog components.

Time for action – showing the search users screen in dialog


Let us see how we can display the search users page (searchUsers.xhtml) in the Dialog component.

  1. Create a CommandButton button whose actionListener triggers open the dialog using the RequestContext.openDialog() method:

    <p:commandButton value="Search Users" actionListener="#{userController.searchUsersForm}" />  
    
    public void searchUsersForm() 
    {
      RequestContext.getCurrentInstance().openDialog("searchUsers");
    }
  2. Create the search users page searchUsers.xhtml as follows:

    <!DOCTYPE html>
    <html xmlns="http://www.w3.org/1999/xhtml"
          xmlns:h="http://java.sun.com/jsf/html"
          xmlns:f="http://java.sun.com/jsf/core"
          xmlns:ui="http://java.sun.com/jsf/facelets"
          xmlns:p="http://primefaces.org/ui">
            <h:head>
                <title>Search Users</title>            
            </h:head>
            <h:body>
                <h:form>
                 <p:inputText value="#{userController...

Time for action – passing data from the search users dialog to the source page


Let us add a new column Select to the DataTable in the searchUsers.xhtml page to select a user, and pass the selected user's details back to source page. Perform the following steps:

  1. Create a DataTable component with a Select column to choose a user row using the following code:

    <p:dataTable id="usersTbl" value="#{userController.searchUsers}" var="user">
      <p:column headerText="EmailId">
        #{user.emailId}
      </p:column>
      <p:column headerText="Name">
        #{user.firstName} #{user.lastName}
      </p:column>
      <p:column headerText="Select">
        <p:commandButton icon="ui-icon-search" actionListener="#{userController.selectSearchUser(user)}" />
      </p:column>
    </p:dataTable>
  2. When the user selects a row (user), close the dialog by passing the selected user object as data:

    public void selectSearchUser(User user){
      RequestContext.getCurrentInstance().closeDialog(user);
    }
  3. Register...

Introducing the ConfirmDialog component


The ConfirmationDialog component is a replacement for the traditional JavaScript confirm dialog with skinning and customization features.

Very common scenarios to display the confirm dialog box is when the user tries to delete some data.

Time for action – creating a confirmation dialog


Let us see how to create a confirmation dialog with Yes and No options.

  1. Create a confirmation dialog using <p:confirmDialog> with two buttons for Yes and No options:

    <h:form id="form1" style="width: 300px; margin-left: 5px;">
      <p:growl/>
      <p:panel header="User Form">
        <h:panelGrid columns="2">
          <h:outputText value="EmailId:" />
          <p:inputText value="admin@gmail.com"/>      
          <p:commandButton value="Delete" onclick="cnfDlg.show()" />
        </h:panelGrid>
      </p:panel>
      <p:confirmDialog widgetVar="cnfDlg" header="Confirmation" message="Are you sure to delete?" >
        <p:commandButton value="Yes" actionListener="#{confirmDialogController.handleDelete}" oncomplete="cnfDlg.hide();" update="form1"/>
        <p:commandButton value="No" onclick="cnfDlg.hide();"/>
      </p:confirmDialog>
      
    </h:form>
  2. Implement the action handler method using the following...

Displaying notifications using the NotificationBar component


The NotificationBar is a component to display notifications as a fixed positioned panel either on top or bottom of the page. As the notification bar is a Panel component, you can place other JSF components inside it. You can use client-side API methods show() and hide() respectively to show and hide the notification bar through the widgetVar value.

Time for action – displaying notification messages


Let us see how to create a simple notification bar to display a message using JavaScript show() and hide() methods.

  1. Create a NotificationBar component to display notification messages and two buttons to show and hide the notification bar widget:

    <p:notificationBar id="bar" widgetVar="notifBar" style="height:20px; background-color: #8B0000;">
      <h:outputText value="There are New Unread Emails in your MailBox." style="color:#FFF;font-size:20px;"/>
    </p:notificationBar>
    <h:form>
      <p:commandButton value="Show" onclick="notifBar.show()"/>
      <p:commandButton value="Hide" onclick="notifBar.hide()"/>
    </h:form>

What just happened?

We have created a notification bar widget using a <p:notificationBar> component. When the Show and Hide buttons are clicked, we have displayed and closed NotificationBar using the client-side JavaScript API calls notifBar.show() and notifBar.hide().

By default, NotificationBar...

Time for action – automatically hiding NotificationBar


In this section we will demonstrate how to display the PrimeFaces NotificationBar component and automatically hide it using the JavaScript setTimeout() function.

  1. Create a NotificationBar widget and buttons to show and hide it using the following code:

    <p:notificationBar id="bar" widgetVar="notifBar" position="top" effect="slide" effectSpeed="slow" style="height: 20px; background-color: #8B0000;">
      <h:outputText value="There are New Unread Emails in your MailBox." style="color:#FFF;font-size:20px;"/>
    </p:notificationBar>
    
    <h:form>
      <p:commandButton value="Show" onclick="notifBar.show()"/>
      <p:commandButton value="Hide" onclick="notifBar.hide()"/>  
      <p:commandButton value="Show &amp; Auto Hide" onclick="showNotifBar()"/>  
    </h:form>
  2. Create an onclick event handler JavaScript function showNotifBar() using the following code:

    <script>
      var timeoutID = null;
      function showNotifBar...

Blocking a region using the BlockUI component


The BlockUI component can be used to block other JSF UI components during AJAX processing. With the special AJAX integration, AJAX requests from any of the trigger components will block the UI component for the onstart event and unblock for the oncomplete event.

We may want to block a particular UI component or even entire page while some background processing is running. For example, when we submit a form, we may want to block the form to prevent users from doing any action on the form until the response is received from the server.

Time for action – blocking the form


In this section, we will demonstrate how to block a specific region, such as a form, while the form submission background process is still running.

  1. Create a user Registration Form and BlockUI component to block the form while registration is inprocess using the following code:

    <p:growl autoUpdate="true"/>
    <h:form id="form1">
      <p:panel header="BlockUI">
      <h:panelGrid columns="2">
        <h:outputLabel value="EmailId" />
        <p:inputText value="#{blockUIController.registerUser.emailId}"/>
        
        <h:outputLabel value="Password" />
        <p:password value="#{blockUIController.registerUser.password}"/>
        
        <p:commandButton id="submitBtn" value="Register" actionListener="#{blockUIController.doRegister}"/>  
      </h:panelGrid>
      </p:panel>
      <p:blockUI block="form1" trigger="submitBtn"/>
    </h:form>
  2. Create an action handler method doRegister():

    public void doRegister() 
    {
      //To simulate...

Understanding PrimeFaces selectors


The jQuery library has great support for selecting DOM elements based on various criteria such as ID, name, or CSS class and so on.

Following are a few examples on how to use jQuery Selectors to select DOM elements:

  • $("p"): All <p> elements

  • $("#userId"): The element with id="userId"

  • $(".navbar"): All elements with class="navbar"

PrimeFaces has integration with the jQuery Selector API for referencing JSF component models. So you can use the jQuery Selector API to choose components to be processed or updated.

In most of the scenarios, using the jQuery Selector API for finding UI components yields better performance as the components are picked by navigating through the DOM tree on the client side instead of navigating through the JSF component tree on the server side and hence reduce the load on the server.

You can give a selector expression to update and process UI components using the following syntax:

process="@(expression)" update="@(expression)"

For example...

Time for action – updating UI components using jQuery Selectors


Let us see how to use the jQuery Selector API to update JSF UI components.

  1. Create a form with some mandatory input fields and commandButtons. When buttons are clicked, update the form or fields using jQuery Selector expressions as follows:

    <h:form id="loginForm" styleClass="myform" style="width: 500px;">
      <p:panel header="Login Form">
      <p:messages/>
      <h:panelGrid columns="2">
        <h:outputText value="EmailId:" />
        <p:inputText value="#{jQuerySelectorController.user.emailId}" required="true" label="EmailId"/>
        
        <h:outputText value="Password:" />
        <p:password value="#{jQuerySelectorController.user.password}" required="true" label="Password"/>
        
        <p:commandButton value="Update Form" actionListener="#{jQuerySelectorController.doLogin}" update="@(#loginForm)"/>
        <p:commandButton value="Update Fields" actionListener="#{jQuerySelectorController.doLogin...

Introducing the search expression framework


PrimeFaces 4.0 introduces a new search expression framework for referencing UI components on both the client and server side with more keywords. In addition to more keywords, the search expression framework also supports nested composite expressions as well, which gives finer control on selecting components.

JSF supports referencing UI components by using component identifiers and also provides some keywords to refer commonly used UI elements such as, @this, @all, @none, and @form.

  • @this: Represents current component

  • @all: Represents whole view

  • @form: Represents closest ancestor form of current component

  • @none: Represents no component

Look at the following form which uses identifiers for partial processing and updating the form:

<h:form id="loginForm">
...
<p:commandButton id="loginBtn" process="loginBtn" update="loginForm"/>
</h:form>

Instead of using component identifiers we can use the keywords so that if the identifiers are changed...

Summary


In this chapter, we have learned about frequently used PrimeFaces UI components such as Messages, Growl, Fragment, Sticky, Dialog, ConfirmDialog, BlockUI, and NotificationBar. We learned how to use RequestContext utility methods and looked into the PrimeFaces jQuery Selectors API integration. Also, we have explored how to use a dialog framework and search expression framework.

In the next chapter, we will learn a very important and interesting topic, PrimeFaces Client Side Validation (CSV) framework, which is introduced in the latest PrimeFaces4.0.

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