Drupal 8 is becoming more and more API-first based. This means a lot of imports and exports of data will be done. A thing you might face here, is that the updating of entity reference fields is a bit tricky. Here I'll show you how it is done.

What are entity references?

Entity references can be a lot of things. For example a refence to:

  • Nodes
  • Files
  • Media
  • Tags

The cool thing is that the referencing is done in the same way for all of them.

The tricky part

When adding entity references, you should specify a target id. This can be a node id, or a file id, ...

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

The tricky part is when using multiple files. You should use the appendItem() function there.

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

$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,
    ]);
  }
}

So, if the node already has a reference attached, we get the value, and we use the appendItem function. 

 

Saved you some valuable time?

Buy me a drink 🍺 to keep me motivated to create free content like this!