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 7. Introducing Advanced Input Components

PrimeFaces provides several advanced input components such as Calendar, Spinner, Slider, Rating, and so on, which can be used to build rich user interfaces. Also, PrimeFaces provides the FileUpload and FileDownload components that simplify the process of uploading and downloading of files and provide an enhanced HTML5-powered FileUpload editor. In addition to these, PrimeFaces provides the CAPTCHA validation component that can be used to prevent spam and bots from crawling into our system.

Calendar is a very commonly-used component. PrimeFaces provides the Calendar component with lots of features and customization options such as inline/pop-up calendar, year/month navigation, customizable locale/date format support, and many more.

The Spinner component comes in very handy when getting input with increment and decrement features with a configurable step value.

In e-commerce applications we can use the Slider component to select a range of prices...

Introducing the Calendar component


Calendar is a date and time picker component that provides the following list of features:

  • Pop-up and inline display modes

  • Localization support

  • Month and year navigator

  • Date and time range restriction

  • Multiple pages calendar

  • Customizable date formats

  • AJAX event support for the dateSelect event

  • Advanced customization for enabling/disabling dates and applying custom styles for dates

A basic Calendar component can be displayed using <p:calendar> as follows:

<p:calendar value="#{userController.registerUser.dob}"/>

The <p:calendar> component provides the following attributes to customize its behavior:

  • mindate: This sets the calendar's minimum visible date.

  • maxdate: This sets the calendar's maximum visible date.

  • pages: This enables multiple page rendering. The default value is 1.

  • disabled: This disables the calendar when set to true. The default value is false.

  • mode: This defines how the calendar will be displayed. The default value is popup. Valid values are...

Time for action – displaying a pop-up Calendar with navigator


Let us see how we can display a pop-up Calendar component when a button is clicked with the custom date format and navigator features.

To do this, create the <p:calendar> component using the navigator and pattern attributes:

<p:calendar value="#{userController.registeredUser.dob}" showOn="button" navigator="true" pattern="EEE, dd MMM, yyyy"/>

What just happened?

We have created a Calendar component and configured it to be displayed when a button icon is clicked on, using the showOn attribute. As we have set navigator="true", year and month drop-down lists are displayed for easy navigation. Also, we have customized the date format to be displayed in the EEE, dd MMM, yyyy format using the pattern attribute. When a date is selected, it will be displayed as Fri, 14 Feb, 2014. This is shown in the following screenshot:

Understanding Internationalization (I18N) and Localization (L10N)

Before discussing how to localize the Calendar...

Time for action – displaying a multipage calendar with Localization and the dateSelect event listener


Let us see how we can display an inline calendar with multiple months displayed in the French locale and register the dateSelect event listener.

  1. Configure the locale-specific Calendar labels in the calendarLocales.js file and save it in the resources/js folder:

    <script type="text/javascript">
      PrimeFaces.locales['tr'] = {
        closeText: 'kapat',
        prevText: 'geri',
        nextText: 'ileri',
        currentText: 'bugün',
        monthNames: ['Ocak','Subat','Mart','Nisan','Mayis','Haziran','Temmuz','Agustos','Eylül','Ekim','Kasim','Aralik'],
        monthNamesShort: ['Oca','Sub','Mar','Nis','May','Haz', 'Tem','Agu','Eyl','Eki','Kas','Ara'],
        dayNames: ['Pazar','Pazartesi','Sali','Çarsamba','Persembe','Cuma','Cumartesi'],
        dayNamesShort: ['Pz','Pt','Sa','Ça','Pe','Cu','Ct'],
        dayNamesMin: ['Pz','Pt','Sa','Ça','Pe','Cu','Ct'],
        weekHeader: 'Hf',
        firstDay: 1,
        isRTL: false,
        showMonthAfterYear...

Time for action – using Calendar with a date range


Let us see how we can use the mindate and maxdate values from backing beans.

  1. Create a Calendar component with a date selection range using the mindate and maxdate attributes:

    <p:calendar value="#{userController.registeredUser.dob}" 
          pattern="dd-MM-yyyy"
          mindate="#{userController.dobMinDate}" 
          maxdate="#{userController.dobMaxDate}"
          showButtonPanel="true"
          showWeek="true" 
          showOtherMonths="true" 
          selectOtherMonths="false" 
          effect="slideDown"
          />
  2. Implement the getMinDate() and getMaxDate() methods to return minimum and maximum dates:

    @ManagedBean
    @RequestScoped
    public class UserController 
    {
      public Date getDobMinDate() throws ParseException 
      {
        return new SimpleDateFormat("dd-MM-yyyy").parse("01-06-2013");
      }
    
      public Date getDobMaxDate() throws ParseException
      {
        return new SimpleDateFormat("dd-MM-yyyy").parse("15-08-2013");
      }
    }

What just happened?

We have specified the date...

Time for action – using Calendar's advanced customization options


Let us see how we can customize the Calendar component to disable Saturday and Sunday dates and apply a custom style.

  1. Create the JavaScript function disableSatSundays() using the following code:

    function disableSatSunDays(date) 
    {
      var day = date.getDay();
      return [(day != 0 && day != 6), 'myCalendar'];
    }
    Create a new custom style myCalendar.
    <style type="text/css">
      .myCalendar
      {
        font-size: 15px;
        background-color: #D3D3D3;
      }
    </style>
  2. Create a Calendar component and configure the beforeShowDay attribute to invoke the disableSatSundays() callback function:

    <p:calendar value="#{userController.registeredUser.dob}" beforeShowDay="disableSatSunDays"/>

What just happened?

We have customized the Calendar to disable all Saturday and Sunday dates using the beforeShowDay attribute and applying the myCalendar CSS style. Even though we restricted selecting Saturdays and Sundays, it is always advisable...

Time for action – Calendar with the time picker options


Let us see how we can use the Calendar component as the date and time picker.

Create a Calendar component with time picker options using the pattern attribute:

<p:calendar value="#{calendarController.meetingTime}" 
    pattern="MM/dd/yyyy HH:mm:ss a"
    stepHour="2" stepMinute="5" stepSecond="10"
          minHour="9" maxHour="18"/>

What just happened?

We have used pattern="MM/dd/yyyy HH:mm:ss a", which makes the Calendar component display the time selection options. Here HH, mm, ss and a represents the hour, minutes, seconds and A.M./P.M. respectively. We have also used other options such as stepHour and stepMinute to specify the step value while dragging the sliders. Similar to the date range, we can also mention the time range using the minHour, maxHour, minMinute, maxMinute, minSecond, and maxSecond attributes. We can also use the Calendar component to display only the time picker options by using the timeOnly="true" attribute...

Time for action – using the Rating component


Let us see how we can use the Rating component with 10 stars and use the rate and cancel AJAX event listeners:

  1. Create a Rating component and register the AJAX listeners for the rate and cancel events, using the following code:

    <p:growl id="growl"/>
    <p:rating value="#{postController.selectedPost.rating}" stars="10">  
      <p:ajax event="rate" listener="#{postController.handlePostRating}" update="growl" />  
      <p:ajax event="cancel" listener="#{postController.handlePostRatingCancel}" update="growl" />  
    </p:rating> 
  2. Implement the event listener methods:

    @ManagedBean
    @RequestScoped
    public class PostController 
    {
      private Post selectedPost;  
        //setters and getters
    
        public void handlePostRating(RateEvent rateEvent) {
          Integer rate = (Integer) rateEvent.getRating();
            JSFUtils.addInfoMessage("Post rated:" +rate);
        }
        
        public void handlePostRatingCancel() {  
            JSFUtils.addInfoMessage("Post...

Time for action – using the Spinner component


Let us see how we can use the Spinner component:

  1. Create a Spinner component to hold a double value, say price, that steps by 0.25 with the $ prefix:

    <p:spinner value="#{spinnerController.price}" prefix="$" stepFactor="0.25" />
  2. Create another Spinner component to hold a discount value with a % suffix and the discount value should be between 0 and 10:

    <p:spinner value="#{spinnerController.discount}" suffix="%" min="0" max="10" />

What just happened?

We have used the <p:spinner> component to create Spinner components with various features such as stepFactor, the min/max boundaries, and prefix/suffix.

However, even if you specify the min and max boundaries, the Spinner component will allow you to enter any value outside the boundaries directly in the text field. We can restrict entering the value in the Spinner input text field manually using the onkeydown event as follows:

<p:spinner value="#{spinnerController.discount}" suffix="%"...

Time for action – using the Slider component


Let us see how to use Slider as a range selector.

Create a Slider component with the range attribute set to true:

<h:panelGrid columns="1" style="margin-bottom:10px"> 
  <h:outputText id="displayRange" value="Between #{sliderController.minPrice} and #{sliderController.maxPrice}"/> 
  <p:slider for="minPriceId1,maxPriceId2" display="displayRange" style="width:300px" range="true" displayTemplate="Between {min} and {max}"/>
  <h:inputHidden id="minPriceId1" value="#{sliderController.minPrice}" />
  <h:inputHidden id="maxPriceId2" value="#{sliderController.maxPrice}" />
</h:panelGrid>

What just happened?

We have used the <p:slider> component along with the range="true" attribute, which makes it as range selector. We bound the Slider's min and max values to two hidden input fields and displayed the selected range values using the displayTemplate attribute.

Slider supports the slideEnd AJAX event that is fired when...

Time for action – using CAPTCHA for user registration


Now, let us see how to use the PrimeFaces Captcha component for user registration.

  1. Create a user registration form with the Captcha component:

    <h:form>  
      <p:messages showDetail="true" autoUpdate="true"/>  
      <h:panelGrid columns="2">
        <h:outputLabel value="EmailId" />
        <p:inputText value="#{userController.registerUser.emailId}" required="true" label="EmailId"/>
    
        <h:outputLabel value="Password" />
        <p:password value="#{userController.registerUser.password}" required="true" label="Password"/>
    
        <p:captcha label="Captcha" theme="red"/>
        <h:outputLabel value="" />
      
        <p:commandButton value="Register" ajax="false" actionListener="#{userController.doRegister}" />
    
      </h:panelGrid>
    </h:form>

What just happened?

We have created the User Registration Form window using the Captcha component along with other required input fields such as EmailId and Password...

Time for action – using the FileUpload component


Let us see how we can use the FileUpload component to upload the user profile image of type .jpg, .jpeg, .gif, or .png, which should be a maximum of 1 MB:

  1. Create a user account form to upload the user image:

    <h:form enctype="multipart/form-data">
      <p:fileUpload 
        fileUploadListener="#{userController.handleUserPicUpload}" 
        allowTypes="/(\.|\/)(gif|jpe?g|png)$/" 
        invalidFileMessage="Only gif, jpg or png type images are allowed"
        sizeLimit="1048576"
        invalidSizeMessage="File size should not exceed 1MB"/>
    </h:form>
  2. Implement the actionListener method to save the uploaded image:

    public void handleUserPicUpload(FileUploadEvent event)
    {  
      UploadedFile uploadedFile = event.getFile();
      String fileName = uploadedFile.getFileName();
      byte[] contents = uploadedFile.getContents();
      //logic to save byte[] 
      FacesMessage msg = new FacesMessage("Succesful", uploadedFile.getFileName()+ " is uploaded.");  
      FacesContext...

Time for action – using the FileDownload component


Let us see how we can use the FileDownload component:

  1. Create the FileDownload component:

    <p:dialog modal="true" widgetVar="statusDialog" header="File Download Status" draggable="false" closable="false" resizable="false">  
      <p:graphicImage value="/resources/images/ajax-loader.gif" />  
    </p:dialog> 
    
    <h:form>
      <p:commandButton id="downloadBtn" value="Download" ajax="false" onclick="PrimeFaces.monitorDownload(onDownloadStart, onDownloadStop)" icon="ui-icon-arrowthick-1-s">  
      <p:fileDownload value="#{userController.userPic}" />  
    </p:commandButton>
    
    </h:form> 
  2. Implement the JavaScript callback methods to show the dialog box when the download starts and close the dialog when the download completes:

    <script type="text/javascript">  
    	function onDownloadStart() 
    	{  
    		statusDialog.show();  
    	}  
    	function onDownloadStop() 
    	{  
    		statusDialog.hide();  
    	}  
    </script>
  3. Implement the managed...

Summary


In this chapter, we have learned how to use various PrimeFaces advanced input components such as Calendar, Slider, Spinner, Rating, FileUpload, and FileDownload.

In the next chapter, we will learn about data components such as DataList, DataGrid, DataTable, and exporting data into PDF/Excel using DataExporter.

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