2

I'm trying to add a preprocess hook to add classes based on taxonomy name to the body css of my drupal installation. I've managed to get all the information about the node based on doing some searching around and trial and error, but I'd like to take it to the next step and get all the taxonomy terms based on the particular node id.

The code I am currently using is the following.

function custom_preprocess_html(&$variables) {
  // Add the node ID and node type to the body class.
  $body_classes = [];
  $nodeFields =\Drupal::service('current_route_match')->getParameter('node')->toArray();

  if (is_array($nodeFields) && count($nodeFields) > 0) {
    if (isset($nodeFields['nid'])) {
      $body_classes[] = 'node-' . $nodeFields['nid'][0]['value'];
    }
    if (isset($nodeFields['type'])) {
      $body_classes[] = $nodeFields['type'][0]['target_id'];
    }
  }

  $variables['attributes']['class'] = $body_classes;
}

It works fine and pulls down the information regarding the node. Based on the answer here it seems like all I should have to do is add the following line to get the taxonomy terms: $taxonomyTerms = $nodefields->get('field_yourfield')->referencedEntities(); but when I do so Drupal throws an error. I'll freely admit I'm new to Drupal 8, so any suggestions about where I'm going wrong (is field_yourfield not something that exists, maybe?) would be greatly appreciated.

1 Answer 1

4

Don’t convert the node to an array, use the node object itself. Then methods will work.

// top of file...
use Drupal\node\NodeInterface;

function custom_preprocess_html(&$variables) {
  $node = \Drupal::routeMatch()->getParameter('node');

  if ($node instanceof NodeInterface) {
    $type = $node->getType();
    $id = $node->id();
    $terms = $node->get('field_yourfield')->referencedEntities();
    // code here for $terms...

    $body_classes[] = 'node-' . $id;
    $body_classes[] = $type;
    // ... etc ...
  }
}

I assume type is node type.. but this is where you want to be. $terms should be a list of Term objects, so you can iterate and grab whatever data you need.

You should also check that the node type is the correct one before doing anything as well as checking for existence of the field to avoid errors.

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.