1
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.

2

That's because groups are not attached to the user directly. At the moment Craft stores the user it hasn't handled the permissions not the user groups.

The workflow is

  1. Handling all kinds of variables and data
  2. Fetch/Create a user
  3. Populate the new field values for the user
  4. Store the user
  5. Handle verifications such as sending them an email
  6. Assign the user to groups and grant them permissions

At the moment your event triggers the user wasn't assigned to the groups.

If you want to change users depending on their groups you should use the Users::EVENT_AFTER_ASSIGN_USER_TO_GROUPS event

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.