Loop through a multi value entity reference field working only on the first selected item 1) I have an entity reference view articles_per_user listing all nodes of type article authored by the current logged in user.

2) On the Article Entity, there is a taxonomy reference field field_article_country referencing the taxonomy vocabulary: "Countries" (One value is allowed)

3) On the User Entity, there is a multi-value taxonomy reference field field_user_article_countries referencing the same taxonomy vocabulary: "Countries" (Unlimited value are allowed)

4) On a Webform, I have an entity reference field articles referencing the above entity reference view 'articles_per_user' with unlimited values where the users can select one or more article.

5) When Webform is submitted, I want to:


Load each selected Article.
Get value of the field_article_country
Load the current logged in user entity.
Set the retrieved value to field_user_article_countries
Save the User entity.


Quick Demonstration:

Say the Current User selected on the Webform 3 articles where:


Article 1 has field_article_country = United States
Article 2 has field_article_country = Egypt
Article 3 has field_article_country = Spain


After the Webform is submitted, the field_user_article_countries at the User Entity must have 3 values selected:


United States
Egypt
Spain


The error I am facing is at field_user_article_countries, I see only one value selected:


United States


Below is my code:

// Function to be fired while submitting the Webform.
public function submitForm(array &amp;$form, FormStateInterface $form_state, WebformSubmissionInterface $webform_submission) {

    // Load the account of current logged in user.
    $CurrentUid = \Drupal::currentUser()-&gt;id();
    $CurrentUser = \Drupal\user\Entity\User::load($CurrentUid);

    // Get the selected 'Articles' Value.
    $ArticleIDs = $values['articles'];     // NIDs

    // Load all "Articles" according to their IDs.
    $Articles = \Drupal\node\Entity\Node::loadMultiple($ArticleIDs);

    // Loop through loaded articles entities.
    foreach ($Articles as $Article) {

    // Get the "Article Country" Value from the loaded article.
    $ArticleCountry = $Article-&gt;get('field_article_country')-&gt;target_id;

    // Set the 'User Country' value on the user account.
    $CurrentUser-&gt;set('field_user_article_countries', $ArticleCountry);
    }

    // Save the User account.
    $CurrentUser-&gt;save();

}
foreach ($Articles as $Article) {

  // Get the "Article Country" Value from the loaded article.
  $ArticleCountry = $Article-&gt;field_article_country-&gt;target_id; // shorter way

  // Set the 'User Country' value on the user account.
  $CurrentUser-&gt;field_user_article_countries[] = ['target_id' =&gt; $ArticleCountry]; // use array

}