Skip to main content
Category:

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();

 

Example with set() method:

$node->set('field_article_images', $fid);

Riadh Rahmi

Senior Web Developer PHP/Drupal & Laravel

I am a senior web developer, I have experience in planning and developing large scale dynamic web solutions especially in Drupal & Laravel.

Web Posts

Search

Page Facebook