Drupal form FAQ: How can I create a date field in a Drupal form (using Drupal 6 or Drupal 7)?
Assuming that you're already comfortable with creating a Drupal form, you can create a Drupal date field widget like this:
# a drupal date field form example $form['birthdate'] = array( '#title' => t('Birthdate'), '#type' => 'date', '#description' => t('Select your birthdate'), '#default_value' => array( 'month' => format_date(time(), 'custom', 'n'), 'day' => format_date(time(), 'custom', 'j'), 'year' => format_date(time(), 'custom', 'Y'), ), );
This Drupal date field example renders three HTML SELECT boxes (combo boxes) that look like this:
Had you been here on the day that screenshot was taken, you would have also seen that the date field defaulted to today's date.
Our date field is created when we specify the 'type' in our Drupal form array:
'#type' => 'date',
In fact, I could create a Drupal form date field as easily as this:
$form['birthdate'] = array( '#title' => t('Birthdate'), '#type' => 'date', );
However, I thought it would be helpful to see the other date field properties shown above.
Drupal date element properties
You can control the Drupal date field element by adjusting date field properties. Some of the most common date field properties are:
- #attributes - lets you set HTML attributes, like 'class'
- #description - 'help' text, typically rendered beneath the form element
- #default_value - the date to default to
- #required - whether the field is required
- #title - a title, typically shown above the form element
You can add even more fields to your Drupal date field definition. The fields you can add are defined in the grid at this Drupal Form API reference page.
(Also, if you're not comfortable with creating a Drupal module or Drupal form, please see my first Drupal form example/tutorial (newbie form example).
Drupal form date field form example - Summary
I hope this Drupal form date field example has been helpful. If you have any questions just leave a note in the Comments section below and I'll be glad to help (if I can).