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)


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? Oct 8 '21 at 8:33
  • where did you put the BaseFieldDefinition un the hook_entity_base_field_info_alter or in the entity class ?
    – berramou
    Oct 9 '21 at 10:14
  • I put it in the class. Oct 11 '21 at 13:28

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.