1

I'm trying to update a user password on save via a custom field (on registration via the back-end - the admin needs to specify a password on registering a user). Is this even possible?

Came across this question How do I change a user's password programmatically in a plugin? and tried using the users.onBeforeSaveUser event to update the $user->newPassword but the user cannot login with the details registered/created.

Any thoughts on above appreciated!

2

You can't use the users.onBeforeSaveUser event to set a user's password as this event happens after the supplied password has been hashed by a private method in the UsersService.

Instead, you could use the users.onSaveUser event, check if a new user has just been saved and if so add the password to the userModel and re-save it. The following is untested, but should do the trick:

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

        // Only fire if new user, this should avoid an infinite loop
        if ($event->params['isNewUser']) {

            // retrieve the userModel from the event
            $user = $event->params['user'];

            // set new password
            $user->newPassword = 'My Super Secret Password';

            // save user
            if (craft()->users->saveUser($user))
            {
                // Password successfully saved!
            }
            else
            {
                // Oops, something went wrong!
            }
        }
    });
  • thanks @SteveRowling - that seems to have done the trick. Seem to be going round in circles on this plugin but seem to be nearly there … :D – Cole Henley Jun 14 '16 at 14:25

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.