Save user group event in Control panel I have a plugin that saves users into a registration group like:

 if (craft()-&gt;request-&gt;isSiteRequest()) {
  //etc 
  $groupId = '1';
  craft()-&gt;userGroups-&gt;assignUserToGroups($user-&gt;id, $groupId);
}


However if i listen for the user save event for the control panel:

if (craft()-&gt;request-&gt;isCpRequest()) {
  //etc 
  $groupId = '1';
  craft()-&gt;userGroups-&gt;assignUserToGroups($user-&gt;id, $groupId);
}


This doesnt work. I also tried passing an array as groupId(s) but the group permission never gets ticked.

Is there another way of assigning a new user saved in the back end to a specific permission group?
It happens here (maybe intended, maybe a bug):

https://github.com/craftcms/cms/tree/master-v2/src/controllers/UsersController.php#L1757

For news users $groupIds is an empty string, which means the expression ($groupIds !== null) becomes true. At line 1780 $groupIds get passed to userGroups->assignUserToGroups() ... inside this method the $groupIds variable is casted to an array.

Eventually this overwrites the groups you've set by your onSaveUser event.



Here is a (dirty) hack that works

craft()-&gt;users-&gt;onSaveUser = function ($event) {

   craft()-&gt;userGroups-&gt;assignUserToGroups($user-&gt;id, $groupId);
   craft()-&gt;params['noGroupReset'] = true;           

};



craft()-&gt;userGroups-&gt;onBeforeAssignUserToGroups = function ($event) {

   $noGroupReset = (isset(craft()-&gt;params['noGroupReset']) &amp;&amp; craft()-&gt;params['noGroupReset'] === true);


   if (count($event-&gt;params['groupIds']) == 0 &amp;&amp; $noGroupReset) {
      $event-&gt;performAction = false; 
   } 

};