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.


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';
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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