1

I am new in Drupal 8. I have created a node with category (taxonomy). Now I don't understand how to get tid by using nid. I am using $node->body->value to get the body field value and use {{ body }}. But to get category id if I use $node->field_category->value, it will display Null in debugging mode.

function THEME_preprocess_node(&$variables) {
  $node = \Drupal::routeMatch()->getParameter('node');
  $variables['body'] = $node->body->value;    // Working fine
  $cat_id = $node->field_category->value;    // Its showing null
  kint($cat_id);
}

So can anyone please tell me how can I get the category id (tid) of a node?

2 Answers 2

2

A reference field doesn't have a property value. You can use entity to load the term or target_id to get the term id:

$tid = $node->field_tags->target_id;
2
0

You can loop over the items like this:

foreach ($node->field_category as $item) {
  $tids[] = $item->target_id;
}

or get the entities like this:

$terms = $node->get('field_category')->referencedEntities();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.