Main menu

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

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.

Click 'read more' to find out how to change the year range.
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)

<?php
$form
['date_of_birth'] = array(
 
'#type' => 'date',
 
'#title' => t('Date of birth'),
 
'#process' => array('custom_date_element'), // ADD #process property
 
'#start_year' => 1900,
 
'#end_year' => format_date(time(), 'custom', 'Y'),
);
?>

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:

<?php
function custom_date_element($element) {
  (...)
  case
'year':
   
$options = drupal_map_assoc(range(1900, 2050));
    break;
?>

5) Replace it by:

<?php
function custom_date_element($element) {
  (...)
  case
'year':
   
$start_year = isset($element['#start_year']) ? $element['#start_year'] : 1900;
   
$end_year = isset($element['#end_year']) ? $element['#end_year'] : format_date(time(), 'custom', 'Y');
   
$options = drupal_map_assoc(range($start_year, $end_year));
    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.

8 comments

by Anonymous on 1 June, 2009 - 15:33

thanks, was very helpful :)

by Trevor on 2 October, 2009 - 20:45

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.

by Anonymous on 30 March, 2010 - 18:08

Very good tip, thanks

Also note that if you do this as part of a php page within drupal then the overriding function must also exist within that page.

by Sajal on 6 July, 2010 - 08:57

Thanks it worked.

by Dieter on 26 July, 2010 - 12:37

It works flawlessly.

by Dieter on 21 October, 2010 - 23:36

Thanks for sharing

by jithin on 2 December, 2010 - 08:13

thanks a lot!

by JulienD on 15 April, 2011 - 09:11

Nice trick, It works fine !

Thanks for sharing :)

Post new comment

Subscribe to Syndicate
© 2011 Sven Decabooter - open source web development. Drupal theme by Kiwi Themes.