3

I am using the UserModel to create a user, and then injecting that into the User API service as is instructed in the documentation. The only thing I am not seeing is how to set the group.

I looked in the Model class and there is no method for setting the group and it's not part of the defineAttributes() method.

In the documentation there is no method to set group, just read only the groups: https://craftcms.com/docs/templating/usermodel#getGroups

Nothing here about it: https://craftcms.com/classreference/services/UsersService

Here is what I am doing to save user.

$user = new UserModel;

$user->username = 'username';
$user->email = 'yourmom@email.com';
// $user->groupID = "group";
$user->firstName = 'first name';
$user->lastName = 'last name';
$user->getContent()->setAttributes([ 'usersAddress' => 'Your face' ]);

craft()->users->saveUser($user);

Am I missing something obvious?

6

It's not documented, but UserGroupsService has a method assignUserToGroups($userId, int|array $groupIds). You'll have to save your user first, but once you have a user id, I believe you can just use that with something like this:

// Original code
$user = new UserModel;

$user->username = 'username';
$user->email = 'user@email.com';
$user->firstName = 'first name';
$user->lastName = 'last name';
$user->getContent()->setAttributes([ 'usersAddress' => 'Your face' ]);

craft()->users->saveUser($user);

// Add to single group
craft()->userGroups->assignUserToGroups($user->id, $groupId);

// OR, add to multiple groups
craft()->userGroups->assignUserToGroups($user->id, [$groupIdOne, $groupIdTwo]);
| improve this answer | |
  • I'll try this. If anyone else know how to do it without saving first that's ideal. But as always Matt Stauffer you handsome intelligent bastard you. – Matt Green Aug 7 '14 at 15:25
  • HA! How YOU doin... – Matt Stauffer Aug 7 '14 at 15:26
  • All worked great! Hope they document that somewhere. – Matt Green Aug 7 '14 at 15:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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