1

I have a module and I want to listen for the saving of a user profile in the front end. Module looks like this.

use Craft;
use yii\base\Event;
use craft\events\UserEvent;
use craft\fields\Users;
use craft\events\ModelEvent;
use yii\base\Module as BaseModule;

My public init looks like this:

public function init(): void { Craft::setAlias('@modules/fetchprofile', DIR);

// Set the controllerNamespace based on whether this is a console or web request
if (Craft::$app->request->isConsoleRequest) {
    $this->controllerNamespace = 'modules\\fetchprofile\\console\\controllers';
} else {
    $this->controllerNamespace = 'modules\\fetchprofile\\controllers';
}

parent::init();

Event::on(
    Users::class, 
    Users::EVENT_AFTER_SAVE, 
     
    function (ModelEvent $event) {
        $user = $event->sender;        
        Craft::dd($user);
    }
);

When dumping the $user object i get nothing. The ModelEvent function is never hit. What am I missing?

Update: SOLVED via User events in Craft 3

 Event::on(
            User::class,
            User::EVENT_AFTER_SAVE,
            function(ModelEvent $event) {
                $user = $event->sender;        
                Craft::dd($user);
            }
        );

1 Answer 1

1

You're importing the wrong class for Users. Try use craft\elements\User instead of use craft\fields\Users. elements\User extends the base elements class which has the event you're trying to use - Here it is in the class reference with an example:

https://docs.craftcms.com/api/v5/craft-base-element.html#event-after-save

4
  • This doesn't work either. Produces error on the calling Event: Event::on(Users::class, Users::EVENT_AFTER_SAVE, Is there even a Users::EVENT_AFTER_SAVE? I swapped this for element but still the results are that the user data is saved but the module does not catch the event. Looking here docs.craftcms.com/api/v5/craft-elements-user.html#events there is no user save event.
    – joomkit
    Commented Oct 22 at 16:33
  • It inherits from base\Element, so the event should still work. Note that the class is called User in the singular, not Users. Check for any other typos. Commented Oct 22 at 16:54
  • Thx James - still no dice
    – joomkit
    Commented Oct 22 at 16:58
  • Interesting - its saving and now I am finding user.errors is saying "unable to save your profile" - its coded in template. How can I get the console for user in frontend when they are not privileged i wonder.?
    – joomkit
    Commented Oct 22 at 17:08

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.