Skip to content

[howto] Inline jQuery UI DatePicker Behavior

Sebastien Briquet edited this page Aug 22, 2021 · 1 revision
abstract class InlineDatePickerBehavior extends JQueryUIBehavior implements IJQueryAjaxAware
{
	private static final long serialVersionUID = 1L;
	public static final String METHOD = "datepicker";

	private JQueryAjaxBehavior onSelectAjaxBehavior;

	/**
	 * Constructor
	 *
	 * @param selector the html selector (ie: "#myId")
	 * @param options the {@link Options}
	 */
	public InlineDatePickerBehavior(String selector, Options options)
	{
	    super(selector, METHOD, options);
	}

	// Methods //

	@Override
	public void bind(Component component)
	{
	    super.bind(component);

	    this.onSelectAjaxBehavior = new OnSelectAjaxBehavior(this);
	    component.add(this.onSelectAjaxBehavior);
	}

	// Events //

	@Override
	public void onConfigure(Component component)
	{
	    this.setOption("onSelect", this.onSelectAjaxBehavior.getCallbackFunction());

	    super.onConfigure(component);
	}

	@Override
	public void onAjax(AjaxRequestTarget target, JQueryEvent event)
	{
	    if (event instanceof SelectEvent)
	    {
		this.onSelect(target, ((SelectEvent) event).getDateText());
	    }
	}

	protected abstract void onSelect(AjaxRequestTarget target, String date);

	// Ajax classes //

	/**
	 * Provides a {@link JQueryAjaxBehavior} that aims to be wired to the 'onSelect' event
	 */
	protected static class OnSelectAjaxBehavior extends JQueryAjaxBehavior
	{
	    private static final long serialVersionUID = 1L;

	    public OnSelectAjaxBehavior(final IJQueryAjaxAware source)
	    {
		super(source);
	    }

	    @Override
	    protected CallbackParameter[] getCallbackParameters()
	    {
		// function( dateText, inst ) { ... }
		return new CallbackParameter[] { CallbackParameter.explicit("dateText"), CallbackParameter.context("inst") };
	    }

	    @Override
	    protected JQueryEvent newEvent()
	    {
		return new SelectEvent();
	    }
	}

	// Event Object //

	/**
	 * Provides an event object that will be broadcasted by the {@link OnSelectAjaxBehavior} callback
	 */
	protected static class SelectEvent extends JQueryEvent
	{
	    private final String date;

	    public SelectEvent()
	    {
		this.date = RequestCycleUtils.getQueryParameterValue("dateText").toString();
	    }

	    public String getDateText()
	    {
		return this.date;
	    }
	}
}
Clone this wiki locally