Score:1

How to update taxonomy field with array of terms?

fr flag

I am having a body like this

{
    "userid": 435,
    "territories_id":[176,139]
}

Where userid is the drupal user id. And I need to update field field_user_territory which is a taxonomy field. I do not want earlier territories to go instead I need to update with 2 more territories.

This is the code I tried.

foreach ($territories_id as $territory_id) {

     
        
            $user = \Drupal\user\Entity\User::load($userid);
            $user->field_user_territory->target_id = $territory_id;
            $user->save();
        
    }

But here the earlier territories got vanished.

Score:3
cn flag

You probably want to append the field items:

$user = \Drupal\user\Entity\User::load($userid);
foreach ($territories_id as $territory_id) {
  // full version (works with autocomplete in an IDE)
  $user->get('field_user_territory')->appendItem(['target_id' => $territory_id]);
  // short version in array syntax
  // $user->field_user_territory[] = $territory_id;
}
$user->save();
Rifas Ali avatar
fr flag
Thanks it worked
Rifas Ali avatar
fr flag
Is there any way to avoid duplication ?
4uk4 avatar
cn flag
Sorry, moved the second version in a comment.
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.