0

I've been editing nodes in code (Drupal 8) like so:

$node = \Drupal\node\Entity\Node::load($nid);
$node->body->value = $body;
$node->title->value = $title;
$node->taxonomy_field->target_id = $value;

If the 'taxonomy_field' entity reference supports multiple terms, how do place them in the $node object? I have tried at least a dozen ways I found on other threads, but none worked. Either errors were thrown, of the code just silently failed.

2 Answers 2

1

The object orientated way would be to use appendItem() from FieldItemList:

$node->field_tags->appendItem([target_id => '1']);

But as the field object provides an array interface you can add items to the field the same way as in a php array:

$node->field_tags[] = '2';
4
  • This doesn't really answer the question of assigning multiple terms, despite the syntax fix.
    – AlxVallejo
    Commented Aug 17, 2023 at 20:48
  • @AlxVallejo, the syntax in the question is fine but it overwrites the field item instead of adding it.
    – 4uk4
    Commented Aug 18, 2023 at 6:37
  • Still doesn't answer the question of assigning multiple ... do you have to appendItem for each individual term? I believe so, but I don't see how setting a single target_id to a taxonomy term is valid.
    – AlxVallejo
    Commented Aug 18, 2023 at 14:10
  • Yes, if you apply both code lines from my answer you have two more items in the field. Normally you probably want to use a loop, though. If you have already built an array with multiple items you can assign the entire array.
    – 4uk4
    Commented Aug 18, 2023 at 14:23
0

$node->field_tags->appendItem([target_id => '1']); worked for me but $node->field_tags[] = '2'; did not.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.