0

I'm trying to build a plugin wherein after a user is created via the normal means via a front end template, the user is immediately logged in.

My module is watching for the after save event on Elements for a User:

Event::on(Elements::class, Elements::EVENT_AFTER_SAVE_ELEMENT, function(ElementEvent $event) {
    if ($event->element instanceof \craft\elements\User && !ElementHelper::isDraftOrRevision($event->element)) {
        return Craft::$app->getModule('my-module')->users->handleCreateLogin($event);
    }
});

Then, handleCreateLogin looks like this:

public function handleCreateLogin(ElementEvent $event)
{
    $user = $event->element;
    $isNewUser = $event->isNew;

    if ($user->can('Admin')) {
        // leave admins alone
        return;
    }

    if ($isNewUser && Craft::$app->user->isGuest) {
        // This is a new user, so log in
        Craft::$app->user->loginByUserId($user->id);
    }
    return;
}

The event triggers fine, but after the user is created I'm greeted by this message:

Call to a member function mergePreferences() on null
vendor/craftcms/cms/src/controllers/UsersController.php at line 1139

which is an error from the UserController's sanity check to see if the user is currently logged in.

According to the docs this is the accepted method, and it worked in a similar fashion in Craft 2. I'm guessing the save isn't complete when trying to redirect after logging in? Or some other bit of unfinished business.

Anyone have any tips or suggestions?

  • Would it be easier to use this? docs.craftcms.com/v3/config/… – Brad Bell Nov 23 '19 at 0:21
  • Thanks @BradBell, I did try that and it didn't seem to change anything, which made me wonder if there was something wonky with how the form was set up - but it's just a normal registration form pointing to the endpoint in the docs. – MikeJ Nov 25 '19 at 14:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.