2
votes

I use PrimeFaces calendar for represent date range (for this I use two calendars). How to change date range in runtime, so that the first calendar range will be less or equal the second calendar value. For example such as time range: http://www.primefaces.org/showcase-ext/sections/timePicker/timeRange.jsf

2

2 Answers

8
votes

You just need to use p:ajax with dateSelect event and update minimum date range of Second calendar in your ManageBean method

Example:-

    <p:calendar id="fromDate" value="#{calendarView.fromDate}">
        <p:ajax event="dateSelect" listener="#{calendarView.onDateSelect}" update="toDate" />
    </p:calendar>

    <p:calendar id="toDate" value="#{calendarView.toDate}"  mindate="#{calendarView.toDateMin}"/>

Hope this helps you :)

1
votes

Addition to the previous answer:

This will do a good job, but not a complete one, still when you edit it manually, you can pass through, and the range will be false. To achieve that, you need to implement a custom JSF date validator.

@FacesValidator("primeDateRangeValidator")
public class PrimeDateRangeValidator implements Validator {

@Override
public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
    if (value == null) {
        return;
    }

    //Leave the null handling of startDate to required="true"
    Object startDateValue = component.getAttributes().get("fromDate");
    if (startDateValue==null) {
        return;
    }

    Date startDate = (Date)startDateValue;
    Date endDate = (Date)value; 
    if (endDate.before(startDate)) {
        throw new ValidatorException(
                FacesMessageUtil.newBundledFacesMessage(FacesMessage.SEVERITY_ERROR, "", "msg.dateRange", ((Calendar)component).getLabel(), startDate));
    }
}

}

And add it to your calendar

<f:validator validatorId="primeDateRangeValidator" />