1

The following doesn't assign an existing user to a group. I've confirmed that both the user and the group exist. Any ideas?

$user = User::find()->username($username)->one();
$user->setGroups([Craft::$app->userGroups->getGroupById(1)]);
Craft::$app->elements->saveElement($user);

I found this answer, which will probably solve it for me, but it leaves me wondering what the purpose of setGroups is.

1

Apparently this is the right way to do it:

$user = User::find()->username($username)->one();
Craft::$app->users->assignUserToGroups($user->id, [1]);

It's unclear how setGroups is supposed to work.

| improve this answer | |

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.