Drupal - Programmatically update an entity reference field
You need to use code similar to the following.
$node = Node::load($nid);
$node->field_code_used_by->target_id = $user_id;
$node->save();
For a multiple-value field, to add the value to the end of the list, use the following code.
$node->field_code_used_by[] = ['target_id' => $user_id];
Another way is setting the entity
property with the entity object, as in the following code.
$node = Node::load($nid);
$user = \Drupal\user\Entity\User::load(1);
$node->field_code_used_by->entity = $user;
$node->save();
Like in D7 the main property of a reference field in D8 is still the target id
:
$node->field_code_used_by->target_id = $user_id;
The entity
property is a computed value. If you put an object in this value, drupal will convert it back to the id before saving it to the dababase.
Multivalue fields
Add an item to a multivalue field:
$node->field_code_used_by[] = ['target_id' => $user_id];
The property target_id
is not necessary, because it is the main property and used by default. So for most fields you can add a value like in a simple php array, which is easy to remember:
$node->field_code_used_by[] = $user_id;
You should be aware of the difference between a single value field and a multiple value field. Code below shows how. Source: https://stefvanlooveren.me/blog/how-programmatically-update-entity-reference-field-drupal-8
$imageIds = [
'3',
'32',
'50'
];
foreach($imageIds as $index => $fid) {
if($index == 0) {
$node->set('field_article_images', $fid);
} else {
$node->get('field_article_images')->appendItem([
'target_id' => $fid,
]);
}
}