2

I have the following code in my plugin.

public function init() 
{
    parent::init();

    craft()->on('users.saveUser', function(Event $event) {

    // only fire if new user
    if ($event->params['isNewUser']) {

        // business logic
        // how do i save result to custom user fields etc...

    }         
 });
}

I guess my question is whether the userRecod has already saved at this point? If so do I need to create another user object, make changes and call .save again? Or is the user still available to me?

2

The user has already been saved at this point and is available as $event->params['user']. If you modify data and save again, however, you will need to be careful of creating an endless loop — not sure what you are trying to do. In this case you should be ok because of the "IsNewUser" conditional.

public function init() 
{
    parent::init();
    craft()->on('users.saveUser', function(Event $event) {

        if ($event->params['isNewUser']) {

            $user = $event->params['user'];
            // update default fields
            $user->firstName = "Bob";
            // update custom fields
            $user->getContent()->setAttributes(array(
                'phone' => "222-222-5555"
            ));
            // save user
            $success = craft()->users->saveUser($user);

            if (!$success) {
                MyPlugin::log('Couldn’t update user "'.$user->username.'"', LogLevel::Error);
            } else {
                MyPlugin::log('Successfully updated user "'.$user->username.'"', LogLevel::Info);
            }
        }

    });
}

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.