Add a date field to Drupal custom form

The other day I needed a date field in one of my custom content forms. I wanted a nice looking datepicker with that too.
Here is how I did it:

First start with your form.

function MODULENAME_form(){ 
   $form = array(); 

   $form['name'] = array( 
     '#type' => 'textfield', 
     '#title' => "Your Name" 
   ); 
   $form['dob'] = array( 
     '#type' => 'date', 
     '#title' => "Your Birth Date" 
   ); 

   $form['submit'] = array( '#type' => 'submit', '#value' => "Click to submit" ); 

   return $form; 
 }
 

This will have the following output:

Now add our datepicker popup with the following code:

$form['dob'] = array(
  '#type' => 'date_popup', 
  '#title' => "Your Birth Date"
);

This will give you something like:

Now you can also add a date_format like this:

$form['dob'] = array(
  '#type' => 'date_popup',
  '#title' => t("Your Birth Date"),
  '#description' => t('Please select your birth date'),
  '#required' => TRUE,
  '#date_format' => 'Y-m-d',
  '#attributes' => array('autocomplete' =>'off','readonly' => 'readonly'),
  '#default_value' => date('Y-m-d'),
 );

Add new comment