Drupal - How do I set the default value of a datetime form element?
use Drupal\Core\Datetime\DrupalDateTime;
and in form
$form['start_date'] = array(
'#type' => 'datetime',
'#title' => t('Start Date'),
'#default_value' => DrupalDateTime::createFromTimestamp(time()),
);
The #default_value
datetime field element expects a DrupalDateTime
object, not a date string.
use Drupal\Core\Datetime\DrupalDateTime;
$form['start_date'] = [
'#type' => 'datetime',
'#title' => t('Start Date'),
'#description' => date($date_format, time()),
'#default_value' => new DrupalDateTime('1978-11-01 10:30:00', 'Europe/Berlin'),
];
For more information see Datetime::processDatetime()
& Datetime
in the API docs.
Also using Drupal 8. This discussion raises an important point - ensure that your date format matches.
I wanted to display the date as d/m/Y but that is not the default format used by the date field:
$today = date("Y-m-d");
$form['general']['endDate'] = ['#type' => 'date','#date_format' => 'd/m/Y','#title' => t('End date'),'#default_value' => $today,];
The clue was in the generated HTML:
data-drupal-date-format="Y-m-d"
The discussion states that the default could be changed but I did not validate that proposition.