1

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.

1 Answer 1

3

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();
3
  • Thanks it worked
    – Rifas Ali
    Commented May 31, 2022 at 10:28
  • Is there any way to avoid duplication ?
    – Rifas Ali
    Commented May 31, 2022 at 10:34
  • Sorry, moved the second version in a comment.
    – 4uk4
    Commented May 31, 2022 at 10:41

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.