1

The article entity has an unlimited multi-value Taxonomy reference field field_article_countries referencing the Taxonomy vocabulary Countriesand the User entity has a single value Taxonomy reference field field_user_countries which referencing the same taxonomy vocabulary Countries.

Programmatically, and comparing to one specific Article, I want to load all users that has have their field_user_countries value = to one of the values available inside the multi-value Taxonomy reference field field_article_countries.

Example: Say Article "ABC" has the field_article_countries with values:

  • Paris
  • Spain
  • London
  • Italy

User "A" has field_user_countries set to:

  • Spain

User "B" has field_user_countries set to:

  • Italy

and User "C" has field_user_countries set to:

  • Turkey

I want programmatically, and based on Article "ABC", to load only User A & User B.

Below is my code:

// Get in array, a list of all "Article Countries" available for the loaded article.
$Article_Countries = $article->field_article_countries->getString();

    // Get Entity Manager to build your query
    $storage = \Drupal::entityTypeManager()
      ->getStorage('user');

    // Get all Users satisfing your conditions
    // For Condition Parameters @See: https://www.drupal.org/docs/8/api/database-api/dynamic-queries/conditions
    $uids = $storage->getQuery()
      ->accessCheck(FALSE)
      //->condition1
      //->condition2
      ->condition('field_user_countries', $Article_Countries, 'IN')
      ->execute();

    // Load all User entities according to their IDs
    $users = \Drupal\user\Entity\User::loadMultiple($uids);

    // Loop through loaded users.  
    foreach ($users as $user) {

    // Do something here.

}

The problem is that only one user is being loaded and not all users !

Any idea what is wrong with my code ?

1 Answer 1

2

$Article_Countries = $article->field_article_countries->getString();

This returns a string

->condition('field_user_countries', $Article_Countries, 'IN')

From the docs, condition with IN accepts an array.

So, you need $Article_Countries to be an array of entity IDs. My first thought was $article->field_article_countries->referencedEntities() to get an array of objects, and then foreach them to build an array of IDs, but that's a bit round-the-houses. So I searched for a neater way and found this: http://drupal.stackexchange.com/a/207715/89581 which suggests:

$ids = array_column($entity->field->getValue(), 'target_id');

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.