6

I need to create a custom contact form in Drupal 8. I wrote all the code to build the form. I just need to set the default value for a datetime form element.

The code I am using to add that form element is the following one.

$form['start_date'] = [
  '#type' => 'datetime',
  '#title' => t('Start date'),
  '#default_value' => time(),
];

The value I am using for the default value doesn't show the expected value. What should I use instead of time()?

4 Answers 4

26

use Drupal\Core\Datetime\DrupalDateTime;

and in form

$form['start_date'] = array(
  '#type' => 'datetime',
  '#title' => t('Start Date'),
  '#default_value' => DrupalDateTime::createFromTimestamp(time()),
);
2
  • 4
    just new DrupalDateTime() also defaults to the currrent time.
    – Berdir
    Commented Aug 10, 2016 at 20:15
  • But for the value, use: '#value' => DrupalDateTime()->format('Y-m-d H:i:s') Commented Nov 11, 2019 at 21:06
5

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.

1
  • The code is using the wrong value for #description.
    – avpaderno
    Commented Aug 3, 2018 at 13:55
2

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.

0

For Drupal 8, the following piece of code works:

// Form element inside buildForm().

$form['start_date'] = [
      '#type' => 'datetime',
      '#title' => t('Start Date'),
      '#default_value' => DrupalDateTime::createFromTimestamp(strtotime($config->get('start_date')))
    ];

// Inside submitForm().

->set('start_date', (string) $form_state->getValue('start_date'))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.