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
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.
Comments
how do i add #after_build?
how do i add #after_build? and i assumed "mymodule_form()" goes to "template.php"?
Well if you are trying to
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 :
Instruction for non coders?
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.
Set a custom year range for a "Date of Birth" date field
Thank you very much. This is what I need.
Thanks Dude..! Keep rocking
Thanks Dude..!
Keep rocking \m/
-
Chintan Umarani
Drupal Developer
www.umarani.com
Thank you very helpful.
Thank you very helpful.
Thank you
Thank you
-
Chintan Umarani
Drupal Developer
www.umarani.com
Great! work
Great! work. . .
Thanks dr1ss
Awsome...!
You are a life saver.
t@n
function mymodule_form_alter
function mymodule_form_alter(array &$form, FormStateInterface $form_state, $form_id) {
if($form_id == 'your_form_id') {
$max_age = date('Y') - 100; // 100 years ago
$min_age = date('Y') - 18; // 15 years ago
$form['field_date_of_birth']['widget'][0]['value']['#date_year_range'] = $max_age.':'.$min_age;
}
}
I'm using this code and works well
Need to set max and min date in Date while doing form alter
Hi Team,
could you please help to set max and min value to date field while altering the form.
One more help.
What is the best way to validate date fields.
Regards,
Govindaraju V