[英]drupal 8 get taxonomy term value in node
Drupal\\node\\Entity\\Node Object ( [in_preview] => [values:protected] => Array ( [vid] => Array ( [x-default] => 1 ) 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. 无法直接获取field_destination值。 It's a taxonomy term attached with the content type. 它是与内容类型相关的分类术语。 Any help appriciated. 任何帮助appriciated。
To build on VJamie's answer. 以VJamie的答案为基础。
You will need to either set a use statement at the top of your script; 您需要在脚本的顶部设置一个use语句;
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. 这将摆脱致命。
You can also use some methods from EntityReferenceFieldItemList: Gets the entities referenced by this field, preserving field item deltas: 您还可以使用EntityReferenceFieldItemList中的一些方法:获取此字段引用的实体,保留字段项增量:
$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. 可以从任何引用类型字段直接访问entity
属性。
$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. 在drupal8中,我们曾经遵循oops方法来获取值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.