How can I set new user accounts to pending status in a Craft 3 module? I have the following code in my site module:

Event::on(
    User::class,
    User::EVENT_BEFORE_SAVE,
    function (ModelEvent $event) {
        /** @var User $user */
        $user = $event-&gt;sender;
        if ($event-&gt;isNew === true) {
            $user-&gt;pending = true;
        }
    }
);


It was working as expected until I updated from Craft 3.0.25 to 3.0.27.1

I think this issue is related to a change in the src/controllers/UsersController.php file as per GitHub https://github.com/craftcms/cms/commit/db089251994329d0fbe082c0d3ff234a01d82c98

Also, I replaced my 3.0.27.1 UsersController.php with one from a 3.0.25 install, and my code works again.

What is the best/correct/official way to set new user accounts to pending status in a module that won't break with future Craft updates?

I tried this:

Event::on(
    Users::class,
    Users::EVENT_BEFORE_ACTIVATE_USER,
    function (UserEvent $event) {
        $event-&gt;isValid = false;
    }
);


but got There was a problem activating the user. when trying to activate the user account.

P.S: Verify email addresses? is disabled in User Settings.
Yeah you’re correct that db089251 is the culprit here, which fixed a bug where user activation events weren’t getting fired when users were first created, if the “Verify email addresses?” setting was disabled.

Your new code is close, but that is going to get called each time Craft tries to activate a user—both when they are first created, and when you try to manually activate a user later on. So you just need to add a condition to your event handler.

As a starting point, maybe just check if it’s a site (front-end) request.

Event::on(
    Users::class,
    Users::EVENT_BEFORE_ACTIVATE_USER,
    function (UserEvent $event) {
        if (Craft::$app-&gt;request-&gt;getIsSiteRequest()) {
            $event-&gt;isValid = false;
        }
    }
);