Primefaces Calendar Component Example Tutorial

Filed Under: JSF

In our previous tutorials, we’ve covered several types of Primefaces components such as Primefaces Dashboard and Primefaces AccordionPanel. This tutorial intended for providing you a full explanation of how Calendar component could be used. This tutorial tends to provide you a Maven project configured to use JSF/Primefaces library. If you’ve ever configured a Maven project for using Primefaces before, it’s important for you looking for JSF/Primefaces introduction.

Calendar component is an input component used to select a date featuring display modes, paging, localization and ajax selection and more.

Calendar Basic Info

Tag Info
Component Class org.primefaces.component.calendar.Calendar
Component Type org.primefaces.component.Calendar
Component Family org.primefaces.component
Renderer Type org.primefaces.component.CalendarRenderer
Renderer Class org.primefaces.component.calendar.CalendarRenderer

Calendar Attributes

Name Default Type Description
id null String Unique identifier of the component
rendered true Boolean Boolean value to specify the rendering of the component.
binding null Object An el expression that maps to a server side
value null java.util.Date Value of the component
converter null Converter/String An el expression or a literal text that defines a converter for the component. When it’s an EL expression, it’s resolved to a converter instance. In case it’s a static text, it must refer to a converter id
immediate false Boolean When set true, process validations logic is executed at apply request values phase for this component.
required false Boolean Marks component as required
validator null MethodExpr A method expression that refers to a method validating the input
valueChangeListener null MethodExpr A method expression that refers to a method for handling a valueChangeEvent
requiredMessage null String Message to be displayed when required field validation fails
converterMessage null String Message to be displayed when conversion fails.
validatorMessage null String Message to be displayed when validation fails.
widgetVar null String Name of the client side widget.
mindate null Date or String Sets calendar’s minimum visible date
maxdate null Date or String Sets calendar’s maximum visible date
pages 1 Integer Enables multiple page rendering.
disabled false Boolean Disables the calendar when set to true.
mode popup String Defines how the calendar will be displayed.
pattern MM/dd/yyyy String DateFormat pattern for localization
locale null Object Locale to be used for labels and conversion.
popupIcon null String Icon of the popup button
popupIconOnly false Boolean When enabled, popup icon is rendered without the button
navigator false Boolean Enables month/year navigator
timeZone null TimeZone String or a java.util.TimeZone instance to specify the timezone used for date conversion, defaults to TimeZone.getDefault()
readonlyInput false Boolean Makes input text of a popup calendar readonly.
showButtonPanel false Boolean Visibility of button panel containing today and done buttons.
effect null String Effect to use when displaying and showing the popup calendar.
effectDuration normal String Duration of the effect.
showOn both String Client side event that displays the popup calendar.
showWeek false Boolean Displays the week number next to each week.
disabledWeekends false Boolean Disables weekend columns.
showOtherMonths false Boolean Displays days belonging to other months.
selectOtherMonths false Boolean Enables selection of days belonging to other months
yearRange null String Year range for the navigator, default “c-10:c+10”
timeOnly false Boolean Shows only timepicker without date.
stepHour 1 Integer Hour steps.
stepMinute 1 Integer Minute steps.
stepSecond 1 Integer Second steps.
minHour 0 Integer Minimum boundary for hour selection.
maxHour 23 Integer Maximum boundary for hour selection.
minMinute 0 Integer Minimum boundary for minute selection.
maxMinute 59 Integer Maximum boundary for hour selection.
minSecond 0 Integer Minimum boundary for second selection.
maxSecond 59 Integer Maximum boundary for second selection.
pagedate null Object Initial date to display if value is null.
accesskey null String Access key that when pressed transfers focus to the input element.
alt null String Alternate textual description of the input field.
autocomplete null String Controls browser autocomplete behavior.
dir null String Direction indication for text that does not inherit directionality. Valid values are LTR and RTL.
label null String A localized user presentable name.
lang null String Code describing the language used in the generated markup for this component.
maxlength null Integer Maximum number of characters that may be entered in this field.
onblur null String Client side callback to execute when input element loses focus.
onchange null String Client side callback to execute when input element loses focus and its value has been modified since gaining focus.
onclick null String Client side callback to execute onclick event.
ondblclick null String Client side callback to execute when input element is double clicked.
onfocus null String Client side callback to execute when input element receives focus.
onkeydown null String Client side callback to execute when a key is pressed down over input element.
onkeypress null String Client side callback to execute when a key is pressed and released over input element.
onkeyup null String Client side callback to execute when a key is released over input element.
onmousedown null String Client side callback to execute when a pointer button is pressed down over input element.
onmousemove null String Client side callback to execute when a pointer button is moved within input element.
onmouseout null String Client side callback to execute when a pointer button is moved away from input element.
onmouseover null String Client side callback to execute when a pointer button is moved onto input element.
onmouseup null String Client side callback to execute when a pointer button is released over input element.
onselect null String Client side callback to execute when text within input element is selected by user.
placeholder null String Specifies a short hint.
readonly false Boolean Flag indicating that this component will prevent changes by the user.
style null String Inline style of the component.
styleClass null String Style class of the component.
size null Integer Number of characters used to determine the width of the input element.
tabindex null Integer Position of the input element in the tabbing order.
title null String Advisory tooltip informaton.
beforeShowDay null String Client side callback to execute before displaying a date, used to customize date display.
mask null String Applies a mask using the pattern.

Getting Started With Calendar

For using Calendar component properly, value attribute must be assigned for Date object. As you would see below.

Primefaces Calendar - Default View

The above demo has been achieved by using the following Primefaces view and CalendarManagedBean.

index.xhtml


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml"
	xmlns:ui="http://java.sun.com/jsf/facelets"
	xmlns:h="http://java.sun.com/jsf/html"
	xmlns:f="http://java.sun.com/jsf/core"
	xmlns:p="http://primefaces.org/ui">
	<h:head>
		<title>Calendar</title>
		<script name="jquery/jquery.js" library="primefaces"></script>
	</h:head>
	<h:body>
	<div style="height:500px">
		<h:form>
			<p:calendar value="#{calendarManagedBean.date}"></p:calendar>
		</h:form>
		</div>
	</h:body>
</html>

package com.journaldev.primefaces.beans;

import java.util.Date;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;

@ManagedBean
@SessionScoped
public class CalendarManagedBean {
	private Date date = new Date();

	public Date getDate() {
		return date;
	}

	public void setDate(Date date) {
		this.date = date;
	}
}

Display Modes

Calendar has two main display modes, popup (default) and inline. The below samples would clarify you using inline as you’ve used the default value.

Primefaces Calendar - Inline View

For creating an instance Calendar component like above, you have to implement the Primefaces view and CalendarManagedBean like below.

index.xhtml


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml"
	xmlns:ui="http://java.sun.com/jsf/facelets"
	xmlns:h="http://java.sun.com/jsf/html"
	xmlns:f="http://java.sun.com/jsf/core"
	xmlns:p="http://primefaces.org/ui">
	<h:head>
		<title>Calendar</title>
		<script name="jquery/jquery.js" library="primefaces"></script>
	</h:head>
	<h:body>
	<div style="height:500px">
		<h:form>
			<p:calendar value="#{calendarManagedBean.date}" mode="inline"></p:calendar>
		</h:form>
		</div>
	</h:body>
</html>

package com.journaldev.primefaces.beans;

import java.util.Date;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;

@ManagedBean
@SessionScoped
public class CalendarManagedBean {
	private Date date = new Date();

	public Date getDate() {
		return date;
	}

	public void setDate(Date date) {
		this.date = date;
	}
}

In case you’ve used the popup default view type, you can control the event that you would your Calendar get displayed once it’s fired. ShowOn attribute listed above, defines the client side event to display the calendar. Valid values are:

  1. focus: When input field receives focus.
  2. button: When the popup button is clicked.
  3. both [Default]: Both focus and button cases.

You’re already experiencing the default behavior, focusing on Calendar input get caused the Calendar component to be displayed. This time we’ve left the displaying mode into popup and at the same time we will provide a button for showOn attribute. Let’s see below what’s the result of:

Primefaces Calendar - Default View - ShowOn Button Clicking

As you’ve noticed above, the Calendar component has never shown if you set the focus, rather it would be displayed once you’ve clicked on the button that attached beside. That’s caused by showOn=”button”. Let’s see the required Primefaces view and the CalendarManagedBean.

index.xhtml


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml"
	xmlns:ui="http://java.sun.com/jsf/facelets"
	xmlns:h="http://java.sun.com/jsf/html"
	xmlns:f="http://java.sun.com/jsf/core"
	xmlns:p="http://primefaces.org/ui">
	<h:head>
		<title>Calendar</title>
		<script name="jquery/jquery.js" library="primefaces"></script>
	</h:head>
	<h:body>
	<div style="height:500px">
		<h:form>
			<p:calendar value="#{calendarManagedBean.date}" showOn="button"></p:calendar>
		</h:form>
		</div>
	</h:body>
</html>

package com.journaldev.primefaces.beans;

import java.util.Date;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;

@ManagedBean
@SessionScoped
public class CalendarManagedBean {
	private Date date = new Date();

	public Date getDate() {
		return date;
	}

	public void setDate(Date date) {
		this.date = date;
	}

}

Calendar Paging

The calendar can also be rendered in multiple pages where each page corresponds to one month. This feature is tuned with the pages attribute.

Primefaces Calendar - Default View - Pages Demo

Once the Calendar component is focused, instead of viewing one month, three months are displayed according to the pages attribute. Let’s see the required Primefaces view changes.

index.xhtml


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml"
	xmlns:ui="http://java.sun.com/jsf/facelets"
	xmlns:h="http://java.sun.com/jsf/html"
	xmlns:f="http://java.sun.com/jsf/core"
	xmlns:p="http://primefaces.org/ui">
	<h:head>
		<title>Calendar</title>
		<script name="jquery/jquery.js" library="primefaces"></script>
	</h:head>
	<h:body>
	<div style="height:500px">
		<h:form>
			<p:calendar value="#{calendarManagedBean.date}" pages="3"></p:calendar>
		</h:form>
		</div>
	</h:body>
</html>

Calendar Localization

Calendar component supported multiple kinds of locales as its default localization get determined by the view’s locale itself. However, default value can be overridden, by providing the locale attribute that can take a locale key as a String or a java.util.locale instance.

For localized the Calendar component you should follow the below steps:

  1. Download your locale translation from here. By default, Calendar component’s language of labels are English and you need to add the necessary translations to your page manually as Primefaces doesn’t include language translations. The provided link here will lead you into a community-driven page that helps you get the required translation. The translation is a simple JavaScript object, as you can adding it into your page by using the <script/> tag.
  2. Specify the wanted locale by using the locale attribute onto Calendar component.

The demonstration below shows you Three Calendar components have localized using German, English, and French receptively.

Primefaces Calendar - German Locale

Primefaces Calendar - English Locale

Primefaces Calendar - Frensh Locale

Now, let’s look at the project directory, JavaScript files and the Primefaces view itself.
Primefaces Calendar Project Directory

index.xhtml


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml"
	xmlns:ui="http://java.sun.com/jsf/facelets"
	xmlns:h="http://java.sun.com/jsf/html"
	xmlns:f="http://java.sun.com/jsf/core"
	xmlns:p="http://primefaces.org/ui">
	<h:head>
		<title>Calendar</title>
		<script name="jquery/jquery.js" library="primefaces"></script>
		<script type="text/javascript" src="de.js"></script>
		<script type="text/javascript" src="fr.js"></script>
		<script type="text/javascript" src="en.js"></script>
	</h:head>
	<h:body>
	<div style="height:500px">
		<h:form>
			<p:calendar value="#{calendarManagedBean.date}" locale="de"></p:calendar>
			<p:calendar value="#{calendarManagedBean.date}" locale="en"></p:calendar>
			<p:calendar value="#{calendarManagedBean.date}" locale="fr"></p:calendar>
		</h:form>
	</div>
	</h:body>
</html>

de.js


PrimeFaces.locales['de'] = {
    closeText: 'Schließen',
    prevText: 'Zurück',
    nextText: 'Weiter',
    monthNames: ['Januar', 'Februar', 'März', 'April', 'Mai', 'Juni', 'Juli', 'August', 'September', 'Oktober', 'November', 'Dezember'],
    monthNamesShort: ['Jan', 'Feb', 'Mär', 'Apr', 'Mai', 'Jun', 'Jul', 'Aug', 'Sep', 'Okt', 'Nov', 'Dez'],
    dayNames: ['Sonntag', 'Montag', 'Dienstag', 'Mittwoch', 'Donnerstag', 'Freitag', 'Samstag'],
    dayNamesShort: ['Son', 'Mon', 'Die', 'Mit', 'Don', 'Fre', 'Sam'],
    dayNamesMin: ['S', 'M', 'D', 'M ', 'D', 'F ', 'S'],
    weekHeader: 'Woche',
    firstDay: 1,
    isRTL: false,
    showMonthAfterYear: false,
    yearSuffix: '',
    timeOnlyTitle: 'Nur Zeit',
    timeText: 'Zeit',
    hourText: 'Stunde',
    minuteText: 'Minute',
    secondText: 'Sekunde',
    currentText: 'Aktuelles Datum',
    ampm: false,
    month: 'Monat',
    week: 'Woche',
    day: 'Tag',
    allDayText: 'Ganzer Tag'
};

fr.js


PrimeFaces.locales ['fr'] = {
    closeText: 'Fermer',
    prevText: 'Précédent',
    nextText: 'Suivant',
    monthNames: ['Janvier', 'Février', 'Mars', 'Avril', 'Mai', 'Juin', 'Juillet', 'Août', 'Septembre', 'Octobre', 'Novembre', 'Décembre' ],
    monthNamesShort: ['Jan', 'Fév', 'Mar', 'Avr', 'Mai', 'Jun', 'Jul', 'Aoû', 'Sep', 'Oct', 'Nov', 'Déc' ],
    dayNames: ['Dimanche', 'Lundi', 'Mardi', 'Mercredi', 'Jeudi', 'Vendredi', 'Samedi'],
    dayNamesShort: ['Dim', 'Lun', 'Mar', 'Mer', 'Jeu', 'Ven', 'Sam'],
    dayNamesMin: ['D', 'L', 'M', 'M', 'J', 'V', 'S'],
    weekHeader: 'Semaine',
    firstDay: 1,
    isRTL: false,
    showMonthAfterYear: false,
    yearSuffix:'',
    timeOnlyTitle: 'Choisir l\'heure',
    timeText: 'Heure',
    hourText: 'Heures',
    minuteText: 'Minutes',
    secondText: 'Secondes',
    currentText: 'Maintenant',
    ampm: false,
    month: 'Mois',
    week: 'Semaine',
    day: 'Jour',
    allDayText: 'Toute la journée'
};

en.js


PrimeFaces.locales ['en_US'] = {
    closeText: 'Close',
    prevText: 'Previous',
    nextText: 'Next',
    monthNames: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December' ],
    monthNamesShort: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ],
    dayNames: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
    dayNamesShort: ['Sun', 'Mon', 'Tue', 'Wed', 'Tue', 'Fri', 'Sat'],
    dayNamesMin: ['S', 'M', 'T', 'W ', 'T', 'F ', 'S'],
    weekHeader: 'Week',
    firstDay: 1,
    isRTL: false,
    showMonthAfterYear: false,
    yearSuffix:'',
    timeOnlyTitle: 'Only Time',
    timeText: 'Time',
    hourText: 'Time',
    minuteText: 'Minute',
    secondText: 'Second',
    currentText: 'Current Date',
    ampm: false,
    month: 'Month',
    week: 'week',
    day: 'Day',
    allDayText: 'All Day',
    messages: {
        'javax.faces.component.UIInput.REQUIRED': '{0}: Validation Error: Value is required.',
        'javax.faces.converter.IntegerConverter.INTEGER': '{2}: \'{0}\' must be a number consisting of one or more digits.',
        'javax.faces.converter.IntegerConverter.INTEGER_detail': '{2}: \'{0}\' must be a number between -2147483648 and 2147483647 Example: {1}',
        'javax.faces.converter.DoubleConverter.DOUBLE': '{2}: \'{0}\' must be a number consisting of one or more digits.',
        'javax.faces.converter.DoubleConverter.DOUBLE_detail': '{2}: \'{0}\' must be a number between 4.9E-324 and 1.7976931348623157E308  Example: {1}',
        'javax.faces.converter.BigDecimalConverter.DECIMAL': '{2}: \'{0}\' must be a signed decimal number.',
        'javax.faces.converter.BigDecimalConverter.DECIMAL_detail': '{2}: \'{0}\' must be a signed decimal number consisting of zero or more digits, that may be followed by a decimal point and fraction.  Example: {1}',
        'javax.faces.converter.BigIntegerConverter.BIGINTEGER': '{2}: \'{0}\' must be a number consisting of one or more digits.',
        'javax.faces.converter.BigIntegerConverter.BIGINTEGER_detail': '{2}: \'{0}\' must be a number consisting of one or more digits. Example: {1}',
        'javax.faces.converter.ByteConverter.BYTE': '{2}: \'{0}\' must be a number between 0 and 255.',
        'javax.faces.converter.ByteConverter.BYTE_detail': '{2}: \'{0}\' must be a number between 0 and 255.  Example: {1}',
        'javax.faces.converter.CharacterConverter.CHARACTER': '{1}: \'{0}\' must be a valid character.',
        'javax.faces.converter.CharacterConverter.CHARACTER_detail': '{1}: \'{0}\' must be a valid ASCII character.',
        'javax.faces.converter.ShortConverter.SHORT': '{2}: \'{0}\' must be a number consisting of one or more digits.',
        'javax.faces.converter.ShortConverter.SHORT_detail': '{2}: \'{0}\' must be a number between -32768 and 32767 Example: {1}',
        'javax.faces.converter.BooleanConverter.BOOLEAN': '{1}: \'{0}\' must be \'true\' or \'false\'',
        'javax.faces.converter.BooleanConverter.BOOLEAN_detail': '{1}: \'{0}\' must be \'true\' or \'false\'.  Any value other than \'true\' will evaluate to \'false\'.',
        'javax.faces.validator.LongRangeValidator.MAXIMUM': '{1}: Validation Error: Value is greater than allowable maximum of \'{0}\'',
        'javax.faces.validator.LongRangeValidator.MINIMUM': '{1}: Validation Error: Value is less than allowable minimum of \'{0}\'',
        'javax.faces.validator.LongRangeValidator.NOT_IN_RANGE': '{2}: Validation Error: Specified attribute is not between the expected values of {0} and {1}.',
        'javax.faces.validator.LongRangeValidator.TYPE={0}': 'Validation Error: Value is not of the correct type.',
        'javax.faces.validator.DoubleRangeValidator.MAXIMUM': '{1}: Validation Error: Value is greater than allowable maximum of \'{0}\'',
        'javax.faces.validator.DoubleRangeValidator.MINIMUM': '{1}: Validation Error: Value is less than allowable minimum of \'{0}\'',
        'javax.faces.validator.DoubleRangeValidator.NOT_IN_RANGE': '{2}: Validation Error: Specified attribute is not between the expected values of {0} and {1}',
        'javax.faces.validator.DoubleRangeValidator.TYPE={0}': 'Validation Error: Value is not of the correct type',
        'javax.faces.converter.FloatConverter.FLOAT': '{2}: \'{0}\' must be a number consisting of one or more digits.',
        'javax.faces.converter.FloatConverter.FLOAT_detail': '{2}: \'{0}\' must be a number between 1.4E-45 and 3.4028235E38  Example: {1}',
        'javax.faces.converter.DateTimeConverter.DATE': '{2}: \'{0}\' could not be understood as a date.',
        'javax.faces.converter.DateTimeConverter.DATE_detail': '{2}: \'{0}\' could not be understood as a date. Example: {1}',
        'javax.faces.converter.DateTimeConverter.TIME': '{2}: \'{0}\' could not be understood as a time.',
        'javax.faces.converter.DateTimeConverter.TIME_detail': '{2}: \'{0}\' could not be understood as a time. Example: {1}',
        'javax.faces.converter.DateTimeConverter.DATETIME': '{2}: \'{0}\' could not be understood as a date and time.',
        'javax.faces.converter.DateTimeConverter.DATETIME_detail': '{2}: \'{0}\' could not be understood as a date and time. Example: {1}',
        'javax.faces.converter.DateTimeConverter.PATTERN_TYPE': '{1}: A \'pattern\' or \'type\' attribute must be specified to convert the value \'{0}\'',
        'javax.faces.converter.NumberConverter.CURRENCY': '{2}: \'{0}\' could not be understood as a currency value.',
        'javax.faces.converter.NumberConverter.CURRENCY_detail': '{2}: \'{0}\' could not be understood as a currency value. Example: {1}',
        'javax.faces.converter.NumberConverter.PERCENT': '{2}: \'{0}\' could not be understood as a percentage.',
        'javax.faces.converter.NumberConverter.PERCENT_detail': '{2}: \'{0}\' could not be understood as a percentage. Example: {1}',
        'javax.faces.converter.NumberConverter.NUMBER': '{2}: \'{0}\' could not be understood as a date.',
        'javax.faces.converter.NumberConverter.NUMBER_detail': '{2}: \'{0}\' is not a number. Example: {1}',
        'javax.faces.converter.NumberConverter.PATTERN': '{2}: \'{0}\' is not a number pattern.',
        'javax.faces.converter.NumberConverter.PATTERN_detail': '{2}: \'{0}\' is not a number pattern. Example: {1}',
        'javax.faces.validator.LengthValidator.MINIMUM': '{1}: Validation Error: Length is less than allowable minimum of \'{0}\'',
        'javax.faces.validator.LengthValidator.MAXIMUM': '{1}: Validation Error: Length is greater than allowable maximum of \'{0}\'',
        'javax.faces.validator.RegexValidator.PATTERN_NOT_SET': 'Regex pattern must be set.',
        'javax.faces.validator.RegexValidator.PATTERN_NOT_SET_detail': 'Regex pattern must be set to non-empty value.',
        'javax.faces.validator.RegexValidator.NOT_MATCHED': 'Regex Pattern not matched',
        'javax.faces.validator.RegexValidator.NOT_MATCHED_detail': 'Regex pattern of \'{0}\' not matched',
        'javax.faces.validator.RegexValidator.MATCH_EXCEPTION': 'Error in regular expression.',
        'javax.faces.validator.RegexValidator.MATCH_EXCEPTION_detail': 'Error in regular expression, \'{0}\''
    }
};

Ajax Behavior Events

Calendar provides a dateSelect ajax behavior event to execute an instant ajax selection whenever a data is selected. If you define a method as a listener, it will be invoked by passing an org.primefaces.event.SelectEvent instance.

Look at the below demonstration

Primefaces Calendar - Fire Ajax Behavior - DateSelect

Primefaces Calendar - Ajax Behavior

 

By now, let’s see the all required files for doing that work.

index.xhtml


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml"
	xmlns:ui="http://java.sun.com/jsf/facelets"
	xmlns:h="http://java.sun.com/jsf/html"
	xmlns:f="http://java.sun.com/jsf/core"
	xmlns:p="http://primefaces.org/ui">
	<h:head>
		<title>Calendar</title>
		<script name="jquery/jquery.js" library="primefaces"></script>
	</h:head>
	<h:body>
	<div style="height:500px">
		<h:form>
			<p:calendar value="#{calendarManagedBean.date}">
				<p:ajax event="dateSelect" listener="#{calendarManagedBean.dateSelectedAction}"></p:ajax>
			</p:calendar>
		</h:form>
	</div>
	</h:body>
</html>

package com.journaldev.primefaces.beans;

import java.util.Date;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;

import org.primefaces.event.SelectEvent;

@ManagedBean
@SessionScoped
public class CalendarManagedBean {
	private Date date = new Date();

	public Date getDate() {
		return date;
	}

	public void setDate(Date date) {
		this.date = date;
	}

	public void dateSelectedAction(SelectEvent e){
		Date date = (Date)e.getObject();
		System.out.println("Date Selected Is ::"+date);
	}
}

One important note mentioned here, In case you’ve used popup as a mode value, regular ajax behavior events like: blur, keyup and more are supported.

Date Ranges

Using mindate and maxdate options, selectable dates can be restricted. Values for these attributes can be a String or java.util.Date.

As you would see below, we’ve enclosed the available dates between 06/20/14 to 06/20/15, so the calendar won’t allow the user to navigate out of specified scope.

Primefaces Calendar - Range Dates - Min Date

Primefaces Calendar - Range Dates - Max Period

As you’ve noticed, no way for exceeding the date period. Now, let’s look at the required files for doing that.

index.xhtml


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml"
	xmlns:ui="http://java.sun.com/jsf/facelets"
	xmlns:h="http://java.sun.com/jsf/html"
	xmlns:f="http://java.sun.com/jsf/core"
	xmlns:p="http://primefaces.org/ui">
	<h:head>
		<title>Calendar</title>
		<script name="jquery/jquery.js" library="primefaces"></script>
	</h:head>
	<h:body>
	<div style="height:500px">
		<h:form>
			<p:calendar value="#{calendarManagedBean.date}" mindate="06/20/14" maxdate="06/20/15"></p:calendar>
		</h:form>
	</div>
	</h:body>
</html>

Advanced Customization

Use beforeShowDay JavaScript callback to customize the look of each date. The callback JavaScript method should return an array of two values; first value would be used for determining whether the date has enabled or disabled, while the second value should be used for determining the date’s style. The below demonstration will show you how could the callback method be used for disabling all the dates in the Calendar component.

Primefaces Calendar - Advanced Customization - Disabled All Dates

And all that we need for applying like that customization has been mentioned in the below Primefaces view.

index.xhtml


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml"
	xmlns:ui="http://java.sun.com/jsf/facelets"
	xmlns:h="http://java.sun.com/jsf/html"
	xmlns:f="http://java.sun.com/jsf/core"
	xmlns:p="http://primefaces.org/ui">
	<h:head>
		<title>Calendar</title>
		<script name="jquery/jquery.js" library="primefaces"></script>
		<script>
			function beforeShowDate(date){
				console.log(date.getMonth());
				return [false,''];
			}
		</script>
	</h:head>
	<h:body>
	<div style="height:500px">
		<h:form>
			<p:calendar value="#{calendarManagedBean.date}" beforeShowDay="beforeShowDate"></p:calendar>
		</h:form>
	</div>
	</h:body>
</html>

Client Side API

Finally, Primefaces has provided an implicit object called PF. It’s possible for all of those want controlling the Calendar through using of JavaScript client code to use the PF implicit object.

Primefaces provides you four methods can be invoked against Calendar object and through the PF object.

  1. getDate(): return the selected date.
  2. setDate(DateAsParameter): sets display date.
  3. disable: Disables calendar.
  4. enable: Enable Calendar.

Let’s see the demonstrations below for respective above methods:

Primefaces Calendar - Client Side API - Get Date

  • Figure above shows you the result of calling getDate().

Primefaces Calendar - Client Side API - SetDate

  • Figure above shows you the result of setDate(), we already set the date to be 20/6/2014.
  • For both remaining methods, the calendar input will be disabled and enabled respectively. And by that, the user won’t be able to focus the input component until it’s enabled again.

Import Attached Source Code Into Your IDE

Many developers may face problems in getting the source code attached here imported into their IDE’s. For those suffering from issues like that, this section has been introduced for them.

For importing the attached source code smoothly, make sure that you follow the below steps:

  • Open your Eclipse IDE. We’ve used latest Eclipse Kepler 4.3.
  • From the project explorer, by Right clicking on – choosing Import  and Import again will cause an import wizard to be opened.
  • From the Maven node, select Existing Maven Project.

Existing Maven Project

  • Click next and browsing your project’s root directory. In our case we’ve browsing Primefaces-Calendar-Sample and click Okay.
  • Wait a while until the wizard recognized your pom.xml file that’s located there.
  • Make sure you’re selected your pom.xml and click next and finish.

Browsing Your Project

  • It’s probably you may got set of errors that are talking about missing configurations or missing libraries like below.Problems Might Be Raised
  • Don’t pay attention for them cause you’ve created your project using Maven while the Eclipse is trying to read the project as Dynamic Web Project.
  • Select all of these errors and remove them and from Project menu choose Clean.
  • If your JDK was configured properly, you’re almost getting a clear result.

Project Compiled Successfully

  • Just deploy your WAR into any of Java EE compliant container and make fun through investigating the Calendar component.

Summary

Calendar component is a component provided by the Primefaces library. This tutorial tends to discuss it and all of its features. Download the project from below link and play around with it to learn more.

Comments

  1. KentDev says:

    I could successfully resolve the problem by old datepicker JQuery version of Primefaces by using JQuery keydown event and Ascii keyboard codes associated with the arrow keys.

  2. Kent Ninh says:

    Old version Primefaces stylesheet overrides the JQuery datepicker. Hence the accessible JQuery datepicker doesn’t work. I have tried suggestions like putting the <h:outputStylesheet in the body, using <f:facet last, etc…still the Primefaces stylesheet and scripts are last in order; i.e. not the one from datepicker. I am thinking about making datepicker accessible in Java code (i.e. keyboard navigation).

  3. Kent Ninh says:

    Can your getDate() and setDate() be modified to go with keyboard navigation (i.e. Arrow keys) please? My actual problem is that the old version Primefaces stylesheet overrides the modern JQuery accessible datepicker stylesheet. While my agency doesn’t want to update Primefaces to a new version, I am required to make the datepicker accessible (i.e. again keyboard navigation by arrow keys. As an example, right arrow key is for next day, etc…)

  4. Ivette says:

    And to give a choice of two dates with two calendars and one form alone and are called by a single event?

  5. Yasir says:

    is there no appendTo property for calendar ?

  6. Mauricio Albanese says:

    Im trying to apply style or styleClass with no success… the p:calendar wont change its size for example… can you give me a hint please? here’s an example of my p:calendar:

    1. kentDev says:

      I successfully changed the datepicker icon color by using JQuery after numerous attempts to override the Primefaces calendar styles.

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages