By mike529


2019-07-09 20:58:56 8 Comments

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.

1 comments

@Jdrupal 2019-07-10 07:34:06

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);
      }
    }
  }
}

Related Questions

Sponsored Content

2 Answered Questions

[SOLVED] What is the name of the table where view modes are stored?

  • 2018-09-06 18:03:22
  • usernameabc
  • 125 View
  • 1 Score
  • 2 Answer
  • Tags:   8 nodes hooks

1 Answered Questions

[SOLVED] How to change the label of title field

  • 2017-12-18 12:11:52
  • user59414
  • 1163 View
  • 0 Score
  • 1 Answer
  • Tags:   8

1 Answered Questions

[SOLVED] How to replace url of taxonomy label link?

  • 2017-10-11 14:02:59
  • florian_drupal
  • 337 View
  • 2 Score
  • 1 Answer
  • Tags:   8

1 Answered Questions

[SOLVED] Display field's label only when any value added to it

0 Answered Questions

How to display entity label using entity reference field checkbox form display

  • 2016-04-21 15:04:37
  • badm
  • 352 View
  • 1 Score
  • 0 Answer
  • Tags:   8 entities

0 Answered Questions

Change node display for purchased products

2 Answered Questions

[SOLVED] Node display mode on taxonomy page

1 Answered Questions

1 Answered Questions

[SOLVED] Node reference field display

  • 2013-02-18 10:08:44
  • Jose A.
  • 793 View
  • 1 Score
  • 1 Answer
  • Tags:   7 nodes entities

5 Answered Questions

[SOLVED] Change the formatting of a label in Drupal 7

  • 2012-01-26 16:25:16
  • Lester Peabody
  • 2967 View
  • 4 Score
  • 5 Answer
  • Tags:   7 theming nodes

Sponsored Content