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.
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.
Very good tip, thanks Also
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.
Thanks!
Thanks it worked.
Thanks
It works flawlessly.
Thanks for sharing
Thanks for sharing
thanks a lot!
thanks a lot!
Nice trick, It works fine !
Nice trick, It works fine !
Thanks for sharing :)