0

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->get('field_article_countries')->getValue();

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

// Save the Book node.
$book-->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?

  • Welcome to Drupal Answers! This is a plain PHP question. In the foreach loop, you aren't adding items to $countries, but you are initializing the variable each time the loop is executed. It can only contain the value assigned the last time the loop is executed. Plus, $book-->save() contains an extra -. – kiamlaluno May 17 at 7:11
3

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->get('field_article_countries')->getValue());
}
// Set the 'countries' values to the node "book".
$book->set('field_book_countries', $countries);
// Save Book node.
$book-->save();
| improve this answer | |