Wicket DatePicker Customization

Working on a project using Apache Wicket as the UI layer.  Wicket provides a built-in date picker using the YUI DatePicker javascript class.  I had a requirement to constrain the DatePicker to only allow work days to be selected (No Saturdays or Sundays).  Spent a day trying to find examples on how to do this and finally stumbled upon an example.  Thought I’d re-post it here in case anyone ever needs to do this again.

The YUI DatePicker class provides hooks that allow you to specify custom renderers.  The method I used was “addWeekdayRenderer”.  This method takes two parameters: the weekday number (1 = Sunday, 7 = Saturday), and the renderer to use for that weekday.

The code is shown below:

package foo.bar.date;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

import org.apache.wicket.extensions.yui.calendar.DatePicker;

public class WorkdayDatePicker extends DatePicker {

private static final long serialVersionUID = 1L;
private final String title;
private final Date maxDate;
private final Date minDate;

public WorkdayDatePicker(final String title, final Date maxDate, final Date minDate) {
super();
this.title = title;
this.maxDate = maxDate;
this.minDate = minDate;
}

@Override
protected void configure(Map widgetProperties) {
super.configure(widgetProperties);
if (maxDate != null) {
widgetProperties.put("maxdate", new SimpleDateFormat("MM/dd/yyyy").format(maxDate));
}
if (minDate != null) {
widgetProperties.put("mindate", new SimpleDateFormat("MM/dd/yyyy").format(minDate));
}
widgetProperties.put("title", title);
}

@Override
protected String getAdditionalJavascript() {
return "var weekendRenderer = function(workingDate, cell) {" +
" cell.innerHTML = '' + this.buildDayLabel(workingDate) + '';" +
" YAHOO.util.Dom.addClass(cell, 'previous');" +
" return YAHOO.widget.Calendar.STOP_RENDER;" +
"};" +
"" +
"${calendar}.addWeekdayRenderer(1, weekendRenderer);" +
"${calendar}.addWeekdayRenderer(7, weekendRenderer);";
}
}

It's only fair to share...
Share on FacebookGoogle+Tweet about this on TwitterShare on LinkedIn

Leave a Reply