Add new items to a multivalue field instead of override existing values I have an Article content type with a multi-values taxonomy reference field (field_article_countries) for the Countries vocabulary. I also have a Book content type with a multi-values taxonomy reference field (field_book_countries) for the same vocabulary.

I am trying to:


Loop through all the loaded articles one by one
Get all the field_article_countries values 
Set those values to field_book_countries
Save the loaded Book node


For example, a Book node (ID 12) has field_book_countries set to none. An Article node (ID 3) has field_article_countries set to Italy; another Article node (ID 40) has field_article_countries set to Greece, Turkey, Egypt, Brazil, Spain.

I want to:


Load the first Article node
Get the value of its field_article_countries (Italy)
Load the Book node and set its value of field_book_countries to Italy
Load the other Article node
Get the values of its field_article_countries (Greece, Turkey, Egypt, Brazil, Spain)
Set the field_book_countries values for the Book node to Greece, Turkey, Egypt, Brazil, Spain, Italy
Save the Book node


The code I am using to achieve this is the following.

$articleIDs = [
  '3',
  '40'
];

// Load all the articles.
$articles = \Drupal\node\Entity\Node::loadMultiple($articleIDs);

// Loop through the loaded articles.
foreach ($articles as $article) {
  // Get the "Countries" Values.
  $countries = $article-&gt;get('field_article_countries')-&gt;getValue();

  // Set the 'countries' values to the node "book".
  $book-&gt;set('field_book_countries', $countries);
  // $book-&gt;field_book_countries[] = ['target_id' =&gt; $countries];         
}

// Save the Book node.
$book--&gt;save();


However, for some reason and during the loop, the new values of field_book_countries are overriding the existing one.

What am I doing wrong?
You need to loop through all articles, saving all countries in an temp array. When the loop finished save the countries in the book node.

For example:

$countries = [];
// Loop through loaded articles.
foreach ($articles as $article) {

    // Get the "Countries" Values.
    $countries = array_merge($countries, $article-&gt;get('field_article_countries')-&gt;getValue());
}
// Set the 'countries' values to the node "book".
$book-&gt;set('field_book_countries', $countries);
// Save Book node.
$book--&gt;save();