2

I am able to retrieve taxonomy terms programmatically, (as long as I only want to reference the default fields, 'tid' and 'name'). But how do I access custom taxonomy fields?

$vid = 'MACHINE_NAME';
$terms = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->loadTree($vid);
foreach ($terms as $term) {
    $tid = $term->tid;
    $term_name = $term->name;

    // REFERENCE CUSTOM FIELD VALUES HERE...

}

I have tried all manor of ways I have seen, but can't get any of them working, eg:

$value = $term->FIELD_NAME->value;
$value = $term->get('FIELD_NAME')->getValue();

How do I reference custom taxonomy term fields by their machine name, from what is returned by getStorage('taxonomy_term')->loadTree($vid)?

  • Either should be correct, but only assuming the field type has a column named value. What type of field is it? – Clive Sep 11 '19 at 16:01
  • Correct, it depends on the field type. Look here for info about how to get the value from an entity reference field, drupal.stackexchange.com/a/284658/72672. – user72672 Sep 11 '19 at 16:05
  • @Clive It's a text field, but I couldn't get either to work earlier. I'm AFK now, so will experiment with getValue() when I get back. Jdrupal, thanks for that useful link! – Neil Hillman Sep 11 '19 at 18:49
  • Just realised this happened to me before, the answer should help :) – Clive Sep 11 '19 at 18:54
3

The entities aren't loaded by default (for performance reasons), but TermStorage::loadTree takes a $load_entities parameter:

If TRUE, a full entity load will occur on the term objects. Otherwise they are partial objects queried directly from the {taxonomy_term_data} table to save execution time and memory consumption when listing large numbers of terms. Defaults to FALSE.

That will give you access to the fields. E.g.

$terms = \Drupal::entityTypeManager()
  ->getStorage('taxonomy_term')
  ->loadTree($vid, 0, NULL, TRUE);
| improve this answer | |
  • Brilliant, thanks @Clive. getValue() returned an array, so I swapped it for getString(), but it's all working now fine! – Neil Hillman Sep 11 '19 at 20:07
  • Thank you! That got me much closer to the solution. In my case, I have a known taxonomy id... i just want the machine_name. Your code above returns an array with every child of the vocabulary - not the paraent. ` An array of term objects that are the children of the vocabulary $vid.` – sea26.2 Mar 24 at 16:28

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.