Community Documentation

Using form_alter to change the default value of a date

Last updated January 30, 2013. Created by afeijo on January 30, 2013.
Log in to edit this page.

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

<?php
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;
  }
}
?>

Page status

No known problems

Log in to edit this page

About this page

Drupal version
Drupal 7.x
Audience
Programmers, Site builders
Level
Intermediate
Keywords
Date, form api, Views

Site Building Guide

Drupal’s online documentation is © 2000-2013 by the individual contributors and can be used in accordance with the Creative Commons License, Attribution-ShareAlike 2.0. PHP code is distributed under the GNU General Public License. Comments on documentation pages are used to improve content and then deleted.
nobody click here