3

Having difficulties creating a new user in a custom controller, here's my implementation:

use craft\records\User;

$user = new User;
$user->firstName = $userData['firstName'];
$user->lastName = $userData['lastName'];
$user->username = $userData['loginName'];
$user->email = $userData['loginName'];
$user->password = $userData['password'];

$response = $user->insert();

Response:

SQLSTATE[HY000]: General error: 1364 Field 'id' doesn't have a default value
The SQL being executed was: INSERT INTO `craft_users` (`firstName`, `lastName`, `username`, `email`, `password`, `dateCreated`, `uid`, `dateUpdated`) VALUES ('Tristan', 'Gemus', 'registertest@gmail.com', 'registertest@gmail.com', 'password', '2019-03-28 15:53:10', '85468ad6-63cc-499d-baf4-32aaaf55bfb2', '2019-03-28 15:53:10')

The response returns false. Thoughts?

3

Take a look at Craft's own UsersController->actionSaveUser().

You're probably looking for something closer to this:

$user = new craft\elements\User();

$user->firstName = $firstName;
$user->lastName = $lastName;
$user->username = $userName;
$user->email = $email;
$user->password = $password;

if ($user->validate(null, false)) {
    Craft::$app->getElements()->saveElement($user, false);
}
1
  • I've found that if you actually want to set the password, you need to use $user->newPassword = $password; Other than that, this works exactly as expected, thanks. – jymbob May 14 '19 at 12:29

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.