1

I would assign the password and send it to the user in an email when I create that user from Backend Control Panel. I have the following code, but I got False return on craft()->users->saveUser($user). I also try to use users.onSaveUser trigger, still no luck. Does anyone know how to save the random password to the user? Thanks

craft()->on('userGroups.onAssignUserToGroups',function(Event $event) {
    $user_id = $event->params['userId'];
    $user = craft()->users->getUserById($user_id);
    $userId = craft()->request->getPost('userId');
    $isNewUser = !$userId;

    $email = new EmailModel();
    $emailSettings = craft()->email->getSettings();
    $email->fromEmail = $emailSettings['emailAddress'];
    $email->sender = $emailSettings['emailAddress'];

    if ($isNewUser) {
        /* generate random password */
        $randomPassword = $this->getRandomString(8,false);

        /* set random password to user */
        $user->newPassword = $randomPassword;

        if (craft()->users->saveUser($user)) {
            $result = "success";
        } else {
            $result = "fail";
        }

        $email->subject = 'confirm created email'
        $email->body = "Text to user".$result;
        $email->toEmail = $user->email;

        craft()->email->sendEmail($email);  
    }
});
  • 1
    After you call saveUser($user), calling $user->getErrors() should return a list of validation errors that occurred when trying to save the user. – Brad Bell Jul 13 '17 at 22:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.