Home‎ > ‎UI‎ > ‎

DatePicker


This is how I disable dates in the GWT DatePicker. For example if I want to disable past or future dates making them not selectable in the DatePicker.
1. Expose the CalendarView for use
2. Add a handler to the DatePicker observing month changes
3. Get the CalendarView and use setEnabledOnDate(Date)

See it used in Shozon.com Show dates selection

1. Expose the DatePicker's CalendarView
public class DatePickerEnhanced extends DatePicker {
   
public static DatePickerEnhanced newInstance() {
       
DefaultMonthSelector monthSelector = new DefaultMonthSelector();
       
CalendarView view = new DefaultCalendarView();
       
CalendarModel model = new CalendarModel();
       
return new DatePickerEnhanced(monthSelector, view, model);
   
}

   
public DatePickerEnhanced() {
       
super(new DefaultMonthSelector(), new DefaultCalendarView(), new CalendarModel());
   
}

   
public DatePickerEnhanced(DefaultMonthSelector monthSelector, CalendarView view, CalendarModel model) {
       
super(monthSelector, view, model);
   
}

   
public CalendarView getCalendarView() {
       
return getView();
   
}
}

2. Add a handler to the DatePicker object to observe month changes
    datePicker.addShowRangeHandler(new ShowRangeHandler<Date>() {
         
public void onShowRange(ShowRangeEvent<Date> dateShowRangeEvent) {
             setValidDates
(dateShowRangeEvent);
         
}
   
});

3. Use the CalendarView to disable/enable dates that can be selected in the calendar of the month.
    private void setValidDates(ShowRangeEvent<Date> dateShowRangeEvent) {
       
Date start = dateShowRangeEvent.getStart();
       
Date end = dateShowRangeEvent.getEnd();

       
Integer daysBetween = CalendarUtil.getDaysBetween(start, end);

       
for (int i = 0; i < daysBetween; i++) {
           
Date date = new Date(start.getTime());
           
CalendarUtil.addDaysToDate(date, i);
            setDatePickable
(date);
       
}
   
}
    private void setDatePickable(Date date) {
       
Boolean enabled = true;
       
if (date.before(getStart())) {
            enabled
= false;
       
} else if (date.after(getFinish())) {
            enabled
= false;
       
}
        datePicker
.getCalendarView().setEnabledOnDate(enabled, date);
   
}



Comments