Aug 21, 2020 in Drupal 8, Snippets

Custom entities provide great control and flexibility because your entire entity resides in code. This snippet shows how to add a field to your entity, with an update hook. Because once the entity is installed, you should be able to add/remove/edit your fields.

Step 1: Add the field to your schema and entity file

Firstly, add the field to your schema and interface declaration just like all the other fields in your entity. 

Step 2: write an update hook 

Below is the code of an update hook in my mymodule.module file. It adds the field api_manager_link to my custom entity api_manager of type api. (like you would add a field organization_link to an entity of node of type organisation):

/**
 * Add 'api_manager_link' field to 'api_manager' entities.
 */
function api_manager_update_8001() {
  $field_storage_definition = BaseFieldDefinition::create('api_manager_link')
    ->setLabel(t('Link mapping'))
    ->setDescription(t('Map link fields with label and url, f.e. documents'))
    ->setRevisionable(FALSE);

  \Drupal::entityDefinitionUpdateManager()
    ->installFieldStorageDefinition('api_manager_link', 'api_manager', 'api', $field_storage_definition);
}

Step 3: update

Because we've put this in an update hook, platforms that already use this entity will get updated once there is a call for updates:

drush updb -y

You're done!