9

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
  • 2
    You could just use variable variables: $node->{$field}[] = ..., but I wouldn’t be surprised if the API offered something more pleasing Commented Nov 8, 2017 at 19:08

1 Answer 1

20

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.

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.