Having an issue with using the event \craft\elements\User::EVENT_AFTER_SAVE in a plug in. I am adding a new user to a group. My goal is to have the newly added user automatically added to the same user group as the logged in user. This is my code:
Event::on(
\craft\elements\User::class,
\craft\elements\User::EVENT_AFTER_SAVE,
function(ModelEvent $event) {
if (Craft::$app->getUser()->getIsAdmin() == false){
$loggedInUser = Craft::$app->getUser();
$userGroupUser = new UserGroup_User();
$userGroupUser->groupId = $loggedInUser->getIdentity()->getGroups()[0]['id'];
$userGroupUser->userId = $event->sender->id;
$result = $userGroupUser->insert();
}
}
);
I have put a breakpoint on the code after the if statement and then checked the users table - the new user is not in the users table yet.
I would expect that the new user would be in the table at this point. Is this transaction being saved and executed later? If so is there something I can do to force the transaction to save the new user?
Is this possible a bug?
I do not get any error messages. Why?
EDIT: I should also mention that the usergroup has permission to add users in their own usergroup.
afterSaveElement
event github.com/craftcms/cms/blob/develop/src/services/…afterSave
is still inside the transaction so if you break it up (via breakpoint) the user isn't inside the table at that moment. The eventAfterSaveElement
is fired after the transaction is done, so after the element is stored