1
votes

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.

My current preprocess code is follows:

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

1 Answers

0
votes

If you are trying to get the referenced term names and add them as body classes, your approach seems a little bit off.

This is what I use:

function CUSTOM_preprocess_html(&$variables) {
  // Entity reference field name.
  $field_name = 'field_tags';
  // Get the node object from the visited page. 
  // If the page is not a node detail page, it'll return NULL.
  $node = \Drupal::request()->attributes->get('node');

  // Let's make sure the node has the field.
  if ($node && $node->hasField($field_name)) {
    $referenced_entities = $node->get($field_name)->referencedEntities();
    foreach ($referenced_entities as $term) {
      $variables['attributes']['class'][] = \Drupal\Component\Utility\Html::cleanCssIdentifier($term->getName());
    }
  }
}