1

I want to add another base field to a Drupal entity. It used to be possible to just change the code for the entity definition and then update it via the Drupal console. But now it has to be done in an update hook.

I've added the following update hook, done drush updb and the process completes without errors. I then did drush cr to clear the cache, and then opened up the edit form for the entity in question and gave it a hard refresh. But the new field has not appeared. Any idea what I'm doing wrong? Thanks. The code is based on this: https://www.drupal.org/node/3034742, section named "Installing a new field storage definition".

function opencase_entities_update_8002() {
  $storage_definition =  \Drupal\Core\Field\BaseFieldDefinition::create('datetime')
      ->setLabel(t('Date and time'))
      ->setDescription(t('When the activity started.'))
      ->setRevisionable(TRUE)
      ->setSettings([
        'datetime_type' => 'date'
      ])
      ->setDefaultValue('2000-01-01')
      ->setDisplayOptions('view', [
        'label' => 'above',
        'weight' => -3,
      ])
      ->setDisplayOptions('form', [
        'weight' => -3,
      ]);

  \Drupal::entityDefinitionUpdateManager()
    ->installFieldStorageDefinition('activity_date_time', 'oc_activity', 'oc_activity', $storage_definition);
}
2
  • 2
    Does you have entity form modes defined? Might need to add this new field to them? – stevekeiretsu Feb 17 '20 at 19:57
  • Thanks but no, not using them – naomi Feb 19 '20 at 12:15
1

The problem lies in your display options configuration (reference 4k4's answer to #244122).

Try this:

function opencase_entities_update_8002() {
  $storage_definition =  \Drupal\Core\Field\BaseFieldDefinition::create('datetime')
      ->setLabel(t('Date and time'))
      ->setDescription(t('When the activity started.'))
      ->setRevisionable(TRUE)
      ->setSettings([
        'datetime_type' => 'date'
      ])
      ->setDefaultValue('2000-01-01')
      ->setDisplayOptions('view', [
        'label' => 'above',
        'type' => 'datetime_default',
        'settings' => [
          'format_type' => 'medium',
        ],
        'weight' => -3,
      ])
      ->setDisplayOptions('form', [
        'type' => 'datetime_default',
        'weight' => -3,
      ]);

  \Drupal::entityDefinitionUpdateManager()
    ->installFieldStorageDefinition('activity_date_time', 'oc_activity', 'oc_activity', $storage_definition);
}

Edit: Don't forget to update your Entity definition as well!

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.