Last updated 3 June 2011. Created on 22 May 2011.
Edited by dr1ss. 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 :

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 :

function mymodule_format_dob($form_element, &$form_state){
    // We unset the current values

    // 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 forums, or join #drupal-support in IRC.


Haidee’s picture

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

dr1ss’s picture

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 :

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"); 
chinita7’s picture

I made a custom module with this instruction
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.

ramana_m’s picture

Thank you very much. This is what I need.

chintan4u’s picture

Thanks Dude..!

Keep rocking \m/

Chintan Umarani
Drupal Developer

aya.y’s picture

Thank you very helpful.

chintan4u’s picture

Thank you

Chintan Umarani
Drupal Developer

jawad.shah’s picture

Great! work. . .
Thanks dr1ss

TanvirAhmad’s picture

You are a life saver.