drupal 8 get taxonomy term value in node

user32012 picture user32012 · May 9, 2016 · Viewed 24.5k times · Source

Drupal\node\Entity\Node Object ( [in_preview] => [values:protected] => Array ( [vid] => Array ( [x-default] => 1 )

        [langcode] => Array
            (
                [x-default] => en
            )

        [field_destination] => Array
            (
                [x-default] => Array
                    (
                        [0] => Array
                            (
                                [target_id] => 2
                            )

                    )

            )

Not able to get field_destination value directly. It's a taxonomy term attached with the content type. Any help appriciated.

Answer

Christian picture Christian · Jul 28, 2016

To build on VJamie's answer.

You will need to either set a use statement at the top of your script;

use Drupal\taxonomy\Entity\Term;

Or, prefix the class instance with the namespace;

$term = \Drupal\taxonomy\Entity\Term::load($node->get('field_destination')->target_id);

That will get rid of the fatals.