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.
=======================================================================
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;
}
}
?>
=======================================================================
- Login to post comments