How to easily alter an entity's base field definition per bundle in Drupal 8

by Mario Steinitz   Last Updated January 07, 2018 11:07 AM

We are using the group module in Drupal 8, which introduces a custom entity "group". This entity features a "label" base field with the title "Title". As groups administrator, you can create several different group types, which are handled as fieldable bundles of the group entity and inherit its label base field.

Depending on the group type, we wish to override the generic label title within forms, views, templates, and so on to e.g. 'Label', 'Name', 'Section', ...

However, the group entity does not expose the label title within its config form as the node module does. So we tried overriding the title using hook_entity_base_field_info_alter() like this:

/**
 * Implements hook_entity_base_field_info_alter().
 */
function mymodule_entity_base_field_info_alter(&$fields, \Drupal\Core\Entity\EntityTypeInterface $entity_type) {
  if ($entity_type->id() == 'group' && !empty($fields['label'])) {
    $fields['label']->setTitle(t('Name'));
  }
}

Which works, but changes the title for all bundles.

Our next try was hook_entity_bundle_field_info_alter(). It exposes bundle information, but it does not allow for base fields to be altered.

How can we alter the base field's title on a per-bundle base without having to extend the group module or manually altering all occurrences of our group entities' field labels?

Tags : 8 fields entities


Related Questions






How to properly delete fields, programmatically?

Updated March 20, 2017 13:07 PM