Wednesday, August 13, 2008

Using date field in drupal forms

Adding a date field into drupal form is very easy. Just declare the form element to be of type 'date'. It automatically presents dropdowns for day, month and year next to each other neatly.


$form['date_of_birth'] = array(

'#type' => 'date',

'#title' => t('Date of Birth'),

'#default_value' => $node->expiry_date,

'#description' => t('Date of Birth')


Now we have the date field in our form. All is well till now -- until we submit the form.

Usually we use $form_values['values']['<field_name>'] to get the value and insert into the database. When we try to use the above value in the database INSERT INTO statement, it gives an error or does not insert the value.

So what is the problem? Actually $form_values['values']['date_of_birth'] is not a regular date string, but is an array containing day, month and year. So you have to create date string using the array before inserting into the database.

Here is an example to create a string suitable to insert into MySql date field:


Now you can use the $date_of_birth_str in the INSERT INTO statement.

No comments: