0

I'm building a custom field and formatter in Drupal 8(and teaching myself how to use Drupal & PHP, so bear with me)

I'm not sure how to pull a parent term 'name' value from a nested array.

Right now, I've got this:

$tid = 15
$parent = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->loadParents($tid);

But I'm not sure how to get the 'name' field so I can use it in my #markup.

I used var_dump to see what was there (can't use kint at the moment. Devel caused issues with some other modules)

Here's the array that came back:

array(1) { 
[3]=> object(Drupal\taxonomy\Entity\Term)#1187 (26) { 
    ["values":protected]=> array(9) { 
        ["tid"]=> array(1) { 
            ["x-default"]=> string(1) "3" 
        } 

        ["vid"]=> array(1) { 
            ["x-default"]=> string(10) "plant_part" 
        } 

        ["uuid"]=> array(1) { 
            ["x-default"]=> string(36) "2xxxxxx6-5xxb-2xx5-8xx7-axxxxxxxxc" 
        } 

        ["langcode"]=> array(1) { 
            ["x-default"]=> string(2) "en" 
        } 

        ["name"]=> array(1) { 
            ["x-default"]=> string(11) "Term wanted" 
        } 

I was trying something like this, but no luck:

 $parent['values']['tid']['x-default']
  • Welcome to Drupal Answers! Please check my answer below. But also note, that this group is not intended to teaching you programming. ;) – Mario Steinitz May 27 '18 at 5:26
0

If you check closely with the var_dump() output, you will see, that you actually load an array of entity objects with the type taxonomy term: https://api.drupal.org/api/drupal/core%21modules%21taxonomy%21src%21Entity%21Term.php/class/Term/8.5.x

This object has a getter method getName() that returns the desired property:

$names = [];

foreach($parent as $term) {
  $names[] = $term->getName();
}

$names_list = implode(', ', $names);
  • Thank you! Sorry for asking such a generic programming question. getName() was exactly what I was missing! – turpentyne May 27 '18 at 5:40

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.