[英]Drupal 9 - Add new terms to existing field programatically
I'm having trouble adding a new term to an existing field on a Drupal 9 website.我在向 Drupal 9 网站上的现有字段添加新术语时遇到问题。 Attempts to set field values work for fields I've tested (ie: text and boolean) but not for taxonomy term reference fields.尝试设置字段值适用于我测试过的字段(即:文本和布尔值),但不适用于分类术语参考字段。 Not sure exactly what I'm missing.不确定我到底错过了什么。
Below is the code I'm currently working with.下面是我目前正在使用的代码。
$nids =[123, 124, 125];
foreach ($nids as $nid) {
/** @var \Drupal\node\NodeInterface $node */
$node = \Drupal::entityTypeManager()->getStorage('node')->load($nid);
$field_category = $node->get('field_category')->getValue();
$categories = [];
$new_category = "100647";
foreach ($field_category as $category) {
$categories[] = $category['target_id'];
};
if (!in_array($new_category, $categories)) {
$categories[] = $new_category;
try {
$node->set('field_category', $categories);
$node->save();
}
catch (\Exception $e) {}
}
}
nice try but you are missing entity reference here.不错的尝试,但您在这里缺少实体参考。 Here is your code with few changes.这是您的代码,几乎没有更改。 First thing is $new_category, what entity type is this.首先是$new_category,这是什么实体类型。 If it is a taxonomy type then here is the code如果它是分类法类型,那么这里是代码
$nids =[123, 124, 125];
foreach ($nids as $nid) {
/** @var \Drupal\node\NodeInterface $node */
$node = \Drupal::entityTypeManager()->getStorage('node')->load($nid);
$categories = [];
$categories = array_column($node->field_category->getValue(), 'target_id');
$new_category = "100647";
if (!in_array($new_category, $categories)) {
$categories[] = $new_category;
}
$total_categories = [];
foreach ($categories as $categoryid) {
$category = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->load($categoryid);
if(!empty($category)) {
$total_categories[] = $category;
}
}
try {
$node->set('field_category', $total_categories);
$node->save();
}
catch (\Exception $e) {}
}
Here you are missing entity reference to field that you are mapping to node.在这里,您缺少对要映射到节点的字段的实体引用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.