4

How do I capture user events in Craft 3? I looked at the documentation but couldn't figure it out. I need to capture after user registration events and after user save events.

Here is what I tried, I know it's not correct but I think I'm pretty close

Event::on(
    Users::class,
    Users::EVENT_AFTER_USER_SAVE,
    function (PluginEvent $event) {
        // do something
    }
);
8

There aren't specific User element save events in Craft 3, but you can listen to EVENT_AFTER_SAVE_ELEMENT and check if the element is a user like so:

Event::on(\craft\services\Elements::class, \craft\services\Elements::EVENT_AFTER_SAVE_ELEMENT, function(Event $event) {
    if ($event->element instanceof \craft\elements\User) {
        // Do your thing.
    }
});

For user activation, there's EVENT_AFTER_VERIFY_EMAIL:

Event::on(\craft\services\Users::class, \craft\services\Users::EVENT_AFTER_VERIFY_EMAIL, function(UserEvent $event) {
    $user = $event->user
});
  • Thanks, this was helpful, it gave me an error for function(UserEvent $event), I changed it to function(Event $event) – Brad Feb 27 at 16:14
3

You can also try User::EVENT_BEFORE_SAVE. I'm not sure that it's documented anywhere, or if it was added after Brad responded, but it might work too.

use yii\base\Event;
use craft\elements\User
use craft\events\ModelEvent;

Event::on(
    User::class,
    User::EVENT_AFTER_SAVE,
    function(ModelEvent $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.