Remove a base field from a custom content entity in Drupal 8

Drupal 8 comes with a new paradigm for the entity fields on content entities (there is also whole new thing of config entities, but this is not within the scope of this post). As with Drupal 7 there were properties and fields for an entity, now everything is a field (base fields, and field api fields via field UI). Similar to entity properties in D7, there are now base fields used in D8. These base fields are not managed through the Field UI but get defined in the entity class via method baseFieldDefinitions(). On installation of the module containing the entity, Drupal automatically performs the DB tasks to create database tables and fields for the entity type and the base fields.

So this blog post is about how to change these base fields later on after installing the module and when having already created entities (having data in the tables) and of course don't want to lose this data when performing change to the entity base fields (otherwise you could just uninstall and reinstall the module, losing all data and also field UI configuration). You need to perform the changes in baseFieldDefinitions() method of the entity class (remove, add, change specific base field definition). But that is not enough to have the changes reflected in the database. If you only change baseFieldDefinitions without getting changes to the database, you will find "Mismatched entity and/or field definitions" error in the Drupal status report.

To actually get the changes to the database you can use hook_update_N in your module.install file.

This is an example about how to delete a base field through hook_update_N:

function modulename_update_8001(&$sandbox) {
  $update_manager = Drupal::service('entity.definition_update_manager');
  $definition = $update_manager->getFieldStorageDefinition('fieldname', 'entity_id');
  return t('Entity: field was uninstalled');

entity_id is the id of the entity as given in the Annotation of the entity (@ContentEntityType).

You can check for other operations (update, install base fields) in EntityDefinitionUpdateManager.

Neuen Kommentar schreiben

Filtered HTML

  • Internet- und E-Mail-Adressen werden automatisch umgewandelt.
  • Zulässige HTML-Tags: <a> <em> <strong> <cite> <blockquote> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • HTML - Zeilenumbrüche und Absätze werden automatisch erzeugt.
  • To post pieces of code, surround them with <code>...</code> tags. For PHP code, you can use <?php ... ?>, which will also colour it based on syntax.

Plain text

  • Keine HTML-Tags erlaubt.
  • Internet- und E-Mail-Adressen werden automatisch umgewandelt.
  • HTML - Zeilenumbrüche und Absätze werden automatisch erzeugt.