I have a profile form with a select menu for a user to choose their nearest location (a Category group.) A user will select their nearest location, it will add the category to their profile and then add them to the corresponding User group.
I would also like to remove the user from their existing group. For example, if they change from London to New York, they should be removed from the London user group and placed in the New York group.
The complication is that they belong to other user groups, which they need to stay in.
Adding to the new location group is working well, but I'm looking for a hand in removing the exisiting one. If anyone has any thoughts on my code below, I would very much appreciate it!
Event::on(
User::class, Element::EVENT_AFTER_SAVE, function (ModelEvent $event) {
if (Craft::$app->getRequest()->getIsConsoleRequest()) {
return;
}
$user = $event->sender;
$userLocation = Craft::$app->getRequest()->getBodyParam('fields[userLocation][0]');
if (!$userLocation) {
return;
}
$newLocationCategory = Craft::$app->getCategories()->getCategoryById($userLocation);
$newLocationGroup = Craft::$app->getUserGroups()->getGroupByHandle($newLocationCategory->title);
$oldLocationCategory = Craft::$app->getCategories()->getCategoryById($user->userLocation->id[0]);
$oldLocationGroup = Craft::$app->getUserGroups()->getGroupByHandle($oldLocationCategory->title);
$currentGroupIds = \array_map(function ($group) {
return (int)$group->id;
}, $user->getGroups());
// Remove the user from their old Location group - this is not working
if (($key = array_search($oldLocationGroup->id, $currentGroupIds)) !== false) {
unset($currentGroupIds[$key]);
}
$finalGroupIds = array_merge($currentGroupIds, [$newLocationGroup->id]);
Craft::$app->getUsers()->assignUserToGroups($user->id, $finalGroupIds);
}
);
$oldUserData = User::findOne($user->id);. I'm not totally sure why that wasn't available just from$userbut I get because it's coming from$event->sender?Thanks for your help!
– supazu Nov 06 '22 at 09:23EVENT_BEFORE_SAVEmeans$oldUserData = User::findOne($user->id);returnsnull. Any thoughts on how I could get around that? – supazu Nov 07 '22 at 08:28EVENT_BEFORE_SAVE,$user->idreturnsnull. Changing toEVENT_AFTER_SAVEsolves that, but then the group isn't removed properly (presumably because the old data is now the new data). I think I might need to think about how to set this up to handle both scenarios. – supazu Nov 08 '22 at 02:58