This one really did give me problems (over 2 days of in the end tearing my hair out), but as usual probably due to my lack of Drupal knowledge. Anyway here is the problem I had and the solution I came up with, which may not be the best way but it worked.
Problem
I had a form that I wanted to allow a date to be selected, this date then needed to be stored in a database table. The date also needed to editable by the user.
- I had a simple form with a '#type' => 'date' field
- A function to load the default data from a table
- A submit function to save the data to a table
I created the table date field to start with as a DATETIME type, the form showed the selection fields for day, month and year and nothing worked - it just would not save and restore the correct dates.
Solution
To cut a very long and tedious story short this is how I solved my problem.
1. Make sure the date field in the table is set up as an SIGNED INTEGER
2. The 'date' type field is an array with the following elements:
- 'day'
- 'month'
- 'year'
at least these were the ones I was interested in.
3. Set the '#default_value' of the date field as
'#default_value' => array('day' => format_date($profile->{'dob'}, 'custom','j'),'month' => format_date($profile->{'dob'}, 'custom', 'n'), 'year' => format_date($profile->{'dob'}, 'custom', 'Y')),
where $profile is the object that holds the loaded data from my table and 'dob' is the field holding the date.
4. When saving the date set by the user convert it as follows:
$dob =mktime(0,0,0,$form_values['dob']['month'],
$form_values['dob']['day'],
$form_values['dob']['year']);
then save into the correct field in the table.
Problem solved, easy when you find the answer but frustrating trying to find it.
NB: You need to set the field to SIGNED INTEGER as mktime will generate a negative value for date before Jan 01 1970.
I'm sure there are other ways of doing this , but I found a solution that suits my query and does not involve using any other modules apart from the core install.
Hi, What about cck date
Hi,
What about cck date field you can also use that.
you're the man ! many
you're the man ! many thanks
any idea how to query using datetime functions using MySQL ?
It helped me..thanks
It helped me..thanks
I was googling for a
I was googling for a solution about date fields
and your article was very helpful for me! ;)
Thanks!
Post new comment