1

I have a content type that has an entity reference field. It's a content type for news articles with a field for tagging the article with taxonomy terms.

I'm attempting to access these terms in a block plugin, however I'm having difficulty. Getting other fields like text fields, and dates work just fine. For example

    $node = \Drupal::routeMatch()->getParameter('node');
    $node->get('body')->value

Successfully returns the contents of the node's body but when I use:

    $node = \Drupal::routeMatch()->getParameter('node');
    $tags = $node->get('field_tags')->value;

$tags comes up empty.

 die(print_r($tags));

Does not display anything. I know it's in there somewhere though because when I use

die(print_r($node));

I do see the tag id's in there.

Is there a way to display the value of an entity reference field for taxonomy terms, in a block plugin?

1

->value is what most field types use but it is in no way restricted to that, they can use whatever they want.

What you want is $node->get('field_tags')->target_id for the ID or $node->get('field_tags')->entity for the referenced term object. You can also loop over it with foreach ($node->get('field_tags') as $item) and then $item->target_id/entity.

As always, have a look at the amazing Entity cheat-sheet here: https://wizzlern.nl/drupal/drupal-8-entity-cheat-sheet for more examples and info.

1

I found that in order to get the values I had to use getValue() instead of ->value like so:

$tags = $node->get('field_tags')->getValue();

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.