I am trying to set the default value for the date field in a custom Entity. The code does not produce any errors. The date field does just not populate with any value. How can I set the default value?

enter image description here

   $fields['date'] = BaseFieldDefinition::create('datetime')
      ->setDescription(t('The date of the entity.'))
      ->setDisplayOptions('view', [
        'label' => 'above',
        'weight' => -6,
      ->setDisplayOptions('form', [
        'weight' => -6,
      ->setDisplayConfigurable('form', TRUE)
      ->setDisplayConfigurable('view', TRUE)

2 Answers 2


To fill default value for the date field, you have two options:

  1. create a DrupalDateTime and set it as default value like the following:

  use Drupal\Core\Datetime\DrupalDateTime;
  use Drupal\datetime\Plugin\Field\FieldType\DateTimeItemInterface;

  $default_date = DrupalDateTime::createFromTimestamp(strtotime("2021-09-09"));
  $default_date = $default_date->format(DateTimeItemInterface::DATETIME_STORAGE_FORMAT);
 // set default value.

  1. or this way

    'default_date_type' => 'custom',
    'default_date'      => '2021-09-09',

Note : if you want the default value to be dynamic take a look at this answer it's more complete Default value for datetime field definition in content entity?

  • Thank I tried both of your sultions. Both did not change anything. The field still displays no value (caches cleared multiple times) like in the screenshot above. I knew about your noted link before but even that did not work here. Any other ideas what I might be doing wrong or how to debug this? Commented Oct 8, 2021 at 8:33
  • where did you put the BaseFieldDefinition un the hook_entity_base_field_info_alter or in the entity class ?
    – berramou
    Commented Oct 9, 2021 at 10:14
  • I put it in the class. Commented Oct 11, 2021 at 13:28

This can be achieved by editing the form class if we want to have some dynamic defaults for the DateTime:

use Drupal\Core\Datetime\DrupalDateTime;

final class FooForm extends ContentEntityForm {

   * {@inheritdoc}
  public function form(array $form, FormStateInterface $form_state) {
    $form = parent::form($form, $form_state);

    // Set the date seven days from now.
    $form['foo_date']['widget'][0]['value']['#default_value'] = DrupalDateTime::createFromTimestamp(time() + 3600 * 24 * 7);

    return $form;

// ...

Your Answer

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

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