Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

drupal 8 get taxonomy term value in node

Tags:

drupal-8

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.

like image 760
user32012 Avatar asked May 09 '16 18:05

user32012


Video Answer


5 Answers

This is the correct way on how to achieve it

use Drupal\taxonomy\Entity\Term;

function modulename_node_presave(Drupal\Core\Entity\EntityInterface $entity) {
    switch ($entity->bundle()) {
        case 'programs':
            $term = Term::load($entity->get('field_program_names')->target_id);
            $name = $term->getName();
            $entity->setTitle($name);
            break;
    }
}
like image 57
Salman Haider Avatar answered Oct 01 '22 22:10

Salman Haider


Do this

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

In drupal8 we used to follow oops approach to get the values.

like image 39
vinay kumar Avatar answered Oct 01 '22 22:10

vinay kumar


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.

like image 17
Christian Avatar answered Oct 13 '22 01:10

Christian


You can also use some methods from EntityReferenceFieldItemList: Gets the entities referenced by this field, preserving field item deltas:

$node->get('field_destination')->referencedEntities();

Hope it will be useful for you

like image 13
wau Avatar answered Oct 13 '22 02:10

wau


The following code will get you the term object you need.

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

If you need the name of that term you can do the following

$name = $term->getName();

Hope this helps out!

like image 9
VJamie Avatar answered Oct 13 '22 01:10

VJamie