Score:0

Filling in default value for datetime field in custom entity

de flag

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')
      ->setLabel(t('Date'))
      ->setDescription(t('The date of the entity.'))
      ->setDefaultValue('2021-09-09')
  
      ->setDisplayOptions('view', [
        'label' => 'above',
        'weight' => -6,
      ])
      ->setDisplayOptions('form', [
        'weight' => -6,
      ])
      ->setDisplayConfigurable('form', TRUE)
      ->setDisplayConfigurable('view', TRUE)
      ->setRequired(TRUE);

Score:1
gb flag

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.
  ->setDefaultValue($default_date)

  1. or this way

  ->setDefaultValue([
    '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?

de flag
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?
berramou avatar
gb flag
where did you put the BaseFieldDefinition un the *hook_entity_base_field_info_alter* or in the entity class ?
de flag
I put it in the class.
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.