how to Programmatically update an entity reference field in Drupal 8 & 9

0
(0)

in this tuto I’ll show you how to update Programmatically  an entity reference field in Drupal 8 & 9.

Examples with User Entity

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

Examples with Images

$node->set('field_article_images', ['target_id' => $fid]);

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

Let’s say we have a bunch of images to add to our node.

$imageIds = [
  '31',
  '32',
  '33'
];

foreach($imageIds as $index => $fid) {
  if($index == 0) {
    $node->set('field_article_images', $fid);
  } else {
    $node->get('field_article_images')->appendItem([
      'target_id' => $fid,
    ]);
  }
}

Similar Posts:

1,002

How useful was this post?

Click on a star to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this post.

Scroll to Top