Main menu

How To: Implement Start and End date fields using regular Drupal 7 Form API

Published by dnovikov on Fri, 10/03/2014 - 15:51

Drupal Date module allows creation of so called "combo" fields in content types, which means you get a combo of "Start date" and "End  date" fields. But what if you want to implement this behavior in your arbitrary form? Well, create two normal "date_popup" fields:

<?php

$form['start_date'] = array(
  '#type' => 'date_popup',
  '#date_format' => 'j M Y',
  '#title' => t('Start date'),
  '#date_label_position' => 'invisible',
  '#date_year_range' => '-0:+3',
);

$form['end_date'] = array(
  '#type' => 'date_popup',
  '#date_format' => 'j M Y',
  '#title' => t('End date'),
  '#date_label_position' => 'invisible',
  '#date_year_range' => '-0:+3',
);

?>

Now if you want the end date to follow the start date - i.e. make it always not less than the start date - you need to add some Javascript. Generally this should be done via '#datepicker_options' option in the form field array, but this does not work for JQuery UI Datepicker events. We will use custom Javascript for this:

<?php

// Attach code to the form.

$form['#attached']['js'] = array(
  drupal_get_path('module', 'mymodule') . '/mymodule_date_popup.js' => array(
    'scope' => 'footer',
  ),
);

?>

And here comes the Javascript. As soon as Datepicker JS is attached to input fields only after the first "focus" event, we need to make sure the Datepicker is already there and the event was fired:

(function ($) {
  Drupal.behaviors.mymoduleDatePopup = {
    attach: function (context, settings) {
      $('#edit-start-date-datepicker-popup-0').one('focus', function() {
        $('#edit-start-date-datepicker-popup-0').datepicker('option', {
          onClose: function(selected) {
            $('#edit-end-date-datepicker-popup-0').one('focus', function() {
              $('#edit-end-date-datepicker-popup-0').datepicker('option', 'minDate', selected);
            });
            $('#edit-end-date-datepicker-popup-0').datepicker('option', 'minDate', selected);
          }
        });
      });
    }
  };
}(jQuery));

Add new comment

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.