A good example of getting the children is posted How to get fields...

I need the machine_id of the parent (or target)

Code below fetches the name;

$product_name_id = $product_name_reference->getValue()[0]['target_id'];
$product_name = \Drupal\taxonomy\Entity\Term::load($product_name_id)->label();

The machine_name is visible under 'values'. How do I get it!

enter image description here

  • 1
    You know in PHPstorm, anything visible to you like that, you can right click and "copy path" and it will give you $foo[bar]->baz[0]['value'] as appropriate? However, it may be protected, in which case that won't help, and it might not be the recommended way (generally preferable to look for a documented API method), which is why I just mention it as a comment and not an answer. Mar 24 '20 at 18:11
  • 1
    @stevekeiretsu which is why I rather use kint() than PhpStorm for inspecting variables, see my guide
    – No Sssweat
    Mar 24 '20 at 20:01
  • @sea26.2 indeed. If the value is protected, you'll want to take a look at the "Available methods" tab, as my guide shows.
    – No Sssweat
    Mar 24 '20 at 20:54
  • 1
    @NoSssweat I'm very much more a fan of xdebug than kint or any other form of printing, but that 'available methods' tab is cool. I never realised that was there. Generally I use PHPStorm for that as well, since if you start typing $foo->get, for example, it will offer autocompletes of available getters. But it's nice to know an alternative, cheers. Mar 25 '20 at 0:48

The machine name is the vid:
if you search for machine_id inside taxonomy module there is no machine_id field declared. enter image description here

But if you look at core/modules/taxonomy/config/schema/taxonomy.schema.yml you can see that:

  type: string
  label: 'Machine name'

So to get the vid (Machine name) you should use getVocabularyId something like:

$product_name_id = $product_name_reference->getValue()[0]['target_id'];;
$product_name = \Drupal\taxonomy\Entity\Term::load($product_name_id);
// Vid or machine name.
$vid = $product_name->getVocabularyId();

I was way overthinking it...


$product = $entity->get('field_products')->entity;
$product_name = $product->get('machine_name')->value;

$product gets the object from the taxonomy item $product_name gets machine name

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.