1

I have a plugin that saves users into a registration group like:

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

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

if (craft()->request->isCpRequest()) {
  //etc 
  $groupId = '1';
  craft()->userGroups->assignUserToGroups($user->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?

0

1 Answer 1

2

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()->users->onSaveUser = function ($event) {

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

};



craft()->userGroups->onBeforeAssignUserToGroups = function ($event) {

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


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

};
2
  • Thanks Oliver - that kinda makes sense if not comfort :). It seems that $groupId can be set via onSaveuser from the front end, and I guess not overwriting the admins choices is a sound reason, but for new users maybe a check could be made. I cant really see a neat solution. Seems that general plugin development around saving users has quite a few gotchas. Thx
    – joomkit
    Jul 11, 2017 at 16:53
  • 1
    @joomkit I've added a workaround Jul 11, 2017 at 17:13

Your Answer

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

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