5

I have a requirement of developing a custom contact form in drupal 8. I am able add all the fields but coming to date time field unable to set the default value to current date.

This is my date field code

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

use Drupal\Core\Datetime\DrupalDateTime;

and in form

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

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.

  • The code is using the wrong value for #description. – kiamlaluno Aug 3 '18 at 13:55
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'))
0

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.