1

I have a custom content type in Drupal 8.6.x. I want to be able to change the text used for a field label based on the value of a taxonomy term reference in the node.

For example, I want to change the field label used for the body field, to display "Description" or "Definition" or "Introduction", etc. based on the value in the taxonomy reference field. This is when rendering the node - I don't need to change the field label on the form. I'll need to alter the label in the full and teaser display modes, and just for the custom content type. I don't need to change any of the text in the body field, just what label is shown above it.

3

You can do this by implementing hook_entity_view_display_alter in a custom module.

Some code like this should work:

function HOOK_entity_view_display_alter(\Drupal\Core\Entity\Display\EntityViewDisplayInterface $display, array $context) {
  if (
    $context['entity_type'] == 'node' &&
    $context['bundle'] == 'CUSTOM_CONTENT_TYPE' &&
    (
      $context['view_mode'] == 'full' ||
      $context['view_mode'] == 'teaser'
    )
  ) {
    foreach ($display->getComponents() as $name => $options) {
      if ($name == 'text' && isset($options['label'])) {
        $node = \Drupal::routeMatch()->getParameter('node');
        $options['label'] = $node->FIELD_TERMS->entity->label();
        $display->setComponent($name, $options);
      }
    }
  }
}

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.