Limit number of years available in standard Drupal Form API date field

Public

In your form code add '#pre_render' to your date form element:

Get raw version
php
  1. $form['date'] = array(
  2. '#title' => t('Date'),
  3. '#type' => 'date',
  4. '#default_value' => array(
  5. 'month' => format_date(time(), 'custom', 'n'),
  6. 'day' => format_date(time(), 'custom', 'j'),
  7. 'year' => format_date(time(), 'custom', 'Y'),
  8. ),
  9. '#pre_render' => array('YOUR_MODULE_limit_years_in_date_callback'),
  10. );

In this function we're going to change #options for year dropdown. In my case I want it to be limited to three years: current, previous and next:

Get raw version
php
  1. function YOUR_MODULE_limit_years_in_date_callback($element) {
  2. // Replace year dropdown with three years: current, previous and next
  3. $element['year']['#options'] = drupal_map_assoc(range(date('Y', strtotime('-1 Year')), date('Y', strtotime('+ 1 Year'))));
  4. return $element;
  5. }