2

I am trying to loop through a taxonomy term's tid, but somehow all the array elements are protected. It was very easy peasy in Drupal 7 with:

 $term_id_1 = $node->field_term['und'][0]['tid'];

I am not sure how I could access tid(here is the kint() screenshot):

enter image description here

and here I how I get this and my broken foreach():

public function setCollection($collection) {
$collection_array = [];
$collection_ids =  \Drupal\taxonomy\Entity\Term::load($collection);
kint($collection_ids);
foreach ($collection_ids as $collection_id) {
  $keys = $collection_id->values;
  foreach ($keys as $key){
    $collection_array[] = $key->tid;
  }
}

$this->collection = $collection_array;

}

Question 1-> Is taxonomy terms are node?

Question 2-> Is this line correct to get the fields?

  $collection_ids =  \Drupal\taxonomy\Entity\Term::load($collection);

Question 3-> Can anyone lead me to get access 'tid' from this protected 'values' array?

Warm regards.

2 Answers 2

3

Yes you can do $term->id() which should return the term id if $term is a Term object. See id().

1

Answer 1 - Taxonomy Terms are an Entity in Drupal 8 (Drupal\taxonomy\Entity\Term), not a node.

Answer 2 - Is your parameter $collection a single ID or an array ID's? If it's a single ID, then yes. If it's an array of ID's then you should be using Term::loadMultiple().

Answer 3 - You can call Term::id() on the object, so in your case it would be $collecion_id->id().

Your Answer

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

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