Using form_alter to change the default value of a date
Last updated on
30 April 2025
If you need to set a default value for an exposed views filter, you can do it like this:
this example code will set a ranged date to have a default value of -30 days for the start date, and today for the end date
function hook_form_views_exposed_form_alter(&$form, $form_state, $form_id) {
switch ($form_state['view']->name) {
case 'my_view_name':
// the Date object works only with this date format:
$datemask = 'Y-m-d';
$form['field_date_value']['min']['#default_value'] = date($datemask, time()-30*86400);
$form['field_date_value']['max']['#default_value'] = date($datemask);
break;
$datemask = 'd/m/Y';
$form['field_date_value']['min']['#date_format'] = $datemask;
$form['field_date_value']['max']['#date_format'] = $datemask;
}
}
Help improve this page
Page status: Not set
You can:
You can:
- Log in, click Edit, and edit this page
- Log in, click Discuss, update the Page status value, and suggest an improvement
- Log in and create a Documentation issue with your suggestion