Reputation: 11
I'm having trouble adding a new term to an existing field on a Drupal 9 website. 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) {}
}
}
Upvotes: 1
Views: 786
Reputation: 33
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. 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.
Upvotes: 2