How to change the date year range on a Form API 'date' element

tags: By default, the range of a date element goes from the year 1900 to 2050. In some cases, we don't want users to enter a year value in the future, so we're going to have to limit the range. 1) Add the '#process' property to your date Form API element, and add a property for the start and end year (or you could hardcode this later if you don't want to make it variable)
  1. $form['date_of_birth'] = array(
  2.   '#type' => 'date',
  3.   '#title' => t('Date of birth'),
  4.   '#process' => array('custom_date_element'), // ADD #process property
  5.   '#start_year' => 1900,
  6.   '#end_year' => format_date(time(), 'custom', 'Y'),
  7. );
2) Open the file /includes/form.inc and find the function expand_date(). 3) Copy the function, and paste it in your own module. Change the name of the function to the value of your #process property (in our case custom_date_element) 4) Find the following code in the function:
  1. function custom_date_element($element) {
  2.   (...)
  3.   case 'year':
  4.     $options = drupal_map_assoc(range(1900, 2050));
  5.     break;
5) Replace it by:
  1. function custom_date_element($element) {
  2.   (...)
  3.   case 'year':
  4.     $start_year = isset($element['#start_year']) ? $element['#start_year'] : 1900;
  5.     $end_year = isset($element['#end_year']) ? $element['#end_year'] : format_date(time(), 'custom', 'Y');
  6.     $options = drupal_map_assoc(range($start_year, $end_year));
  7.     break;
6) Now your form element should be within the range you supplied. Alternately you could also not use the #start_year and #end_year properties, but just change the range in your copied function, if you don't want to make them variable.

Submitted by Sven on Sat, 29/11/2008 - 12:07 2 comments

thanks, was very helpful :)

thanks, was very helpful :)

thanks!

Also, you can put your custom_date_element($element) in template.php instead of the module file.

I did it this way because I have multiple modules calling the function, but I realistically should have all of these modules consolidated, but just an FYI.

Thanks again for the greatness.

Post new comment

The content of this field is kept private and will not be shown publicly.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.

More information about formatting options

  • Search

  • On the web

      • Sven Decabooter on Twitter
      • Sven Decabooter on LinkedIn
      • Sven Decabooter on Facebook
      • Sven Decabooter on Delicious
      • Sven Decabooter on LastFM
      • Sven Decabooter on FriendFeed
  • Drupal

    • Individual member of Drupal Association

      View Sven Decabooter's profile on drupal.org