drupal 8 get taxonomy term value in node

妖精的绣舞 提交于 2019-12-03 07:28:42
Christian

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.

wau

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

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!

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;
    }
}

entity property can be accessed directly from any reference type field.

$node = 'myNode';
$termEntity = $node->get('field_taxonomy_reference')->entity;
if ($termEntity instanceof TermInterface) {
  $termLabel = $termEntity->label();
}

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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!