Event::on(\craft\services\Elements::class, \craft\services\Elements::EVENT_AFTER_SAVE_ELEMENT, function(Event $event) {
if ($event->element instanceof \craft\elements\User) {
$user = Craft::$app->getUsers()->getUserById($event->element->id);
if ($user->isInGroup('abc')) {
// Do something
} else {
// Do something different
}
}
});
I created a C3 module on pluginfactory.io. The code above works just fine in detecting when a user is saved/updated.
For sake of simplicity I have two user groups 1) abc
2) def
.
When I uncheck the user from def
and check him into abc
(or the other way around), and save the user, my code won't register that the user group has changed, but thinks the user is still in the previously selected group. If I re-save the user (without changing groups), suddenly the code sees the correct group.
I assume that despite using EVENT_AFTER_SAVE_ELEMENT
, the system still saves the user group change to the db after the Event
triggers. Could that be it?
It's weird though, because any other field I pull from the user, e.g. if I change their email, my code is able to pick up the new email on the first save, so why not the change in user group?
Any assistance is greatly appreciated, cheers!
Edit: Made problem clearer to understand.