0

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);

2 Answers 2

1

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?

3
  • 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
0

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.