Programmatically update an entity reference field I know I can update (or set a value for) an entity reference field in Drupal 7 with code similar to the following.

 $node['field_code_used_by'][LANGUAGE_NONE][0]['target_id'] = $id;


I want to programmatically set a value for my user entity reference field in Drupal 8. 

I tried with $node-&gt;field_code_used_by-&gt;setValue(1); and $node-&gt;field_code_used_by-&gt;entity-&gt;value = 1; but neither of them worked.

How can I set the value for an entity reference field?
You need to use code similar to the following.

    $node = Node::load($nid);     
    $node-&gt;field_code_used_by-&gt;target_id = $user_id;
    $node-&gt;save();


For a multiple-value field, to add the value to the end of the list, use the following code.

$node-&gt;field_code_used_by[] = ['target_id' =&gt; $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-&gt;field_code_used_by-&gt;entity = $user;
    $node-&gt;save();