Last updated June 3, 2011. Created by dr1ss on May 22, 2011.
Log in to edit this page.

Hey guys, I was working on a custom "profile" module for one of my websites. I needed to add a "Date of birth" field...
Well, by default Drupal creates a select element for the year and applies a range from 1900 to 2050... This is cool but it is not what I needed in this case, so I'm gonna show you how to set your own year range easily.

Ok first, you need to add an #after_build to your date field and assign a custom function name. Here is an example :

<?php
function mymodule_form(){
       
$form = array();
       
$form['dob'] = array(
         
'#type' => 'date',
         
'#title' => "Date de naissance",
         
'#after_build' => array("mymodule_format_dob")
        );
        return
$form;
}
?>

Now we add our custom function to alter our date element :

<?php
function mymodule_format_dob($form_element, &$form_state){
   
// We unset the current values
   
unset($form_element['year']['#options']);
   
// Now we set the range we want
   
$max_age = date('Y') - 100; // 100 years ago
   
$min_age = date('Y') - 7; // 7 years ago
    // Now we populate the array
   
$form_element['year']['#options'] = array();
    foreach (
range($max_age, $min_age) as $year){
       
$form_element['year']['#options'][$year] = $year;
    }
   
// We return our modified element
   
return $form_element;
}
?>

You're done ! now you just need to edit the $min_age and $max_age to fit your needs.

Looking for support? Visit the Drupal.org forums, or join #drupal-support in IRC.

Comments

how do i add #after_build? and i assumed "mymodule_form()" goes to "template.php"?

Well if you are trying to alter an existing form you better use hook_form_alter, it works pretty much the same since you get the $form variable that you can play with :

<?php
function mytheme_form_alter(&$form, &$form_state, $form_id) {
    switch (
$form_id) {
        case
"user_profile_form": // You enter the form id of the form
            // And here you add the after_build to the existing date field
           
$form['datefield']['#after_build'] = array("mytheme_format_dob");
        break;
    }
}
?>

I made a custom module with this instruction http://drupal.org/node/580948
I changed "user_profile_form" to ''user_register'' which I think is the form ID in my case.
And also ['datefield'] to ['profile_birthdate'] which I think is the from name in my case.
However it still doesn't work. Is there anything els I have to modify?
Thank you.

Thank you very much. This is what I need.

Thanks Dude..!

Keep rocking \m/

-
Chintan Umarani
Drupal Developer
www.umarani.com

Thank you very helpful.

Thank you

-
Chintan Umarani
Drupal Developer
www.umarani.com

Great! work. . .
Thanks dr1ss