Answers.Body: <p>You can assign a user to certain groups via</p>
  
  <pre><code>Craft::$app-&gt;getUsers()-&gt;assignUserToGroups($user-&gt;id, [1,2,3]);
  </code></pre>
  
  <p>Would assign them to the groups with the ids 1, 2 and 3</p>
  
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2018-10-02T20:08:27.750Z
Answers.LastActivityDate: 2018-10-02T20:08:27.750Z
Answers.UserDisplayName: Robin Schambach
Body: <p>Using Craft::Pro Edition, I want to add a specific UserGroup to an existing User in my module. I tried it this way, but the group is not saved.</p>
  
  <pre><code>$userGroup = Craft::$app-&gt;userGroups-&gt;getGroupByHandle('partner');
  $user-&gt;setGroups([$userGroup]);
  $success = Craft::$app-&gt;elements-&gt;saveElement($user);
  </code></pre>
  
  <p>After (successful) saveElement(), $user->getGroups() still returns an empty array.</p>
  
  <p>When I add the group in the Admin CP, it works, but it needs a password confirmation. </p>
  
Tags: <craft-pro><user-groups>
Title: Set UserGroups for existing User
ThreadText: # Set UserGroups for existing User
  
  (Asked by: username_0 on 2018-10-02)
  
  Using Craft::Pro Edition, I want to add a specific UserGroup to an existing User in my module. I tried it this way, but the group is not saved.
  
  ```
  $userGroup = Craft::$app->userGroups->getGroupByHandle('partner');
  $user->setGroups([$userGroup]);
  $success = Craft::$app->elements->saveElement($user);
  
  ```
  
  After (successful) saveElement(), $user->getGroups() still returns an empty array.
  
  When I add the group in the Admin CP, it works, but it needs a password confirmation.
  
  **Tags:** craft-pro, user-groups
  
  
  ---
  
  ## 1 answers
  
  ### Answer by username_1 on 2018-10-02. Score: 3 | Accepted answer
  
  You can assign a user to certain groups via
  
  ```
  Craft::$app->getUsers()->assignUserToGroups($user->id, [1,2,3]);
  
  ```
  
  Would assign them to the groups with the ids 1, 2 and 3
  
  
  ---
  
  