1

I'm trying to make a very basic plugin that will send an email alert to a User if an Admin changes their User Group.

I thought I could use the onBeforeSaveUser to get the User's current User Group, and then use the onSaveUser event to compare that with the Event's User Group - and then if they differ, do the mail sending.

It doesn't work, and I don't know why. Both events always get the same value for the User Group. What am I not understanding correctly?

private $existingGroups = NULL;

public function init()
{
    craft()->on('users.onBeforeSaveUser', function(Event $event) {
        $eventUser = $event->params['user']; // get the user we are editing

        $user = craft()->users->getUserById($eventUser->id); // get that user's existing information, before we edit it

        $this->existingGroups = $user->getGroups(); // store the groups the User belongs to
        GroupNotificationPlugin::log("existingGroup: " . $this->existingGroups[0]->name, LogLevel::Info);
    });

    craft()->on('users.onSaveUser', function(Event $event) {
        $user = $event->params['user']; // get the user we are editing

        GroupNotificationPlugin::log("Was: " . $this->existingGroups[0]->name, LogLevel::Info);
        GroupNotificationPlugin::log("Now: " . $user->getGroups()[0]->name, LogLevel::Info);

        if($this->existingGroups[0]->name != $user->getGroups()[0]->name){
            GroupNotificationPlugin::log("Changing group", LogLevel::Info);
        }
    });
}

Was: XXX and Now: XXX are always reporting the same, even when I know that I have changed the User Group (unchecking the old one, checking a new one, saving).

2

The problem is that both onSaveUser and onBeforeSaveUser get fired from UsersService->saveUser() and user group assignment happens in the UsersController->actionSaveUser() after UsersService->saveUser() has already been called.

You should probably be using onBeforeAssignUserToGroups and onAssignUserToGroups instead.

0

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.