1

I understand that I can append values to an entity reference field to a node normally with this method

$node->field_tags[] = [
    'target_id' => $my_id,
  ];

However I have a function like so

function addTag($node,$field,$id){
$node->set($field,[
    'target_id' => $id,
  ]);
}

In other words I have to anticipate any field the user supplies. Looking at the node class here

https://api.drupal.org/api/drupal/core!modules!node!src!Entity!Node.php/class/Node/8.2.x

I did discover the set function that lets me specify a field and a value but I don't believe that this would append to an array of entities in a field.

How would I append to an entity reference field to a node if the field name is supplied in a variable?

  • 1
    You could just use variable variables: $node->{$field}[] = ..., but I wouldn’t be surprised if the API offered something more pleasing – Clive Nov 8 '17 at 19:08
3

Yes, the class Node is a good starting point to look for an OOP way:

Click on get(), which returns a field object FieldItemList, where you can use the method appendItem():

$node->get($field)->appendItem([
  'target_id' => $id,
]);

Replace ->get() with {} and ->appendItem() with [] and you get the shorter version which @Clive mentioned in the comment:

$node->{$field}[] = $id;

This is possible because of the magic method ContentEntityBase::__get and the ArrayAccess interface the field implements. I've also dropped target_id, because you don't need this for the main property of a field.

  • Great that worked! What's better practice? The oop way or the other? – Matt Nov 9 '17 at 16:27
  • You can't go wrong by using OOP. But I've seen both and all possible combination in between. – 4k4 Nov 9 '17 at 16:40

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.