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

1 Answered Questions

How can I dynamically change the display format?

  • 2013-07-09 00:21:35
  • Brett Porter
  • 602 View
  • 0 Score
  • 1 Answer
  • Tags:   entities

2 Answered Questions

[SOLVED] How to change a fields label name based on another fields value?

  • 2016-04-11 14:45:40
  • herci
  • 982 View
  • 3 Score
  • 2 Answer
  • Tags:   entities

1 Answered Questions

[SOLVED] Show field label when using tokens in "Global Custom Text" field in Views?

3 Answered Questions

[SOLVED] How to display the node id as a field (with label)

  • 2011-07-21 16:03:51
  • Nicola Peluchetti
  • 3684 View
  • 3 Score
  • 3 Answer
  • Tags:   7 entities

2 Answered Questions

[SOLVED] Node display mode on taxonomy page

1 Answered Questions

[SOLVED] Entity Reference- How do I display more than one view mode?

  • 2013-02-05 02:22:38
  • cayerdis
  • 663 View
  • 4 Score
  • 1 Answer
  • Tags:   7 entities

1 Answered Questions

[SOLVED] Node reference field display

  • 2013-02-18 10:08:44
  • Jose A.
  • 796 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
  • 2975 View
  • 4 Score
  • 5 Answer
  • Tags:   7 theming nodes

Sponsored Content