6

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
    }
);

2 Answers 2

12

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
});
1
  • Thanks, this was helpful, it gave me an error for function(UserEvent $event), I changed it to function(Event $event)
    – Brad
    Commented Feb 27, 2019 at 16:14
4

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) {
        ...
    }
);
1
  • This worked for me, thank you!!
    – iamkeir
    Commented Mar 29, 2022 at 17:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.