1

I am adding new users inside of the Craft controller as part of the frontend user import script. This is the code:

$user = new User();
$user->pending = true;
$user->username = $email;
$user->firstName = $firstName;
$user->lastName = $lastName;
$user->email = $email;
$user->passwordResetRequired = false;
$user->validate(null, false);
Craft::$app->getElements()->saveElement($user, false);

The problem is that if I try to import two users with the same email addresses they just get imported and that's obviously something I don't want to happen. How can I prevent that and silently skip the users with existing email addresses.

I could check the user's existence by querying it in the database but I would like to avoid any unnecessary db queries because there will be thousands of users imported at the same time. That validation line looks promising but I'm not finding any useful instructions in the docs.

1 Answer 1

3

Screenshot of PHPStorm code showing the name of the second parameter of the Save Element function is Run Validation

You're passing false as the second parameter of your saveElement call... that parameter means you're skipping the built-in validation which should catch this error for you. If you get rid of that you should then receive a warning in the logs when processing existing users, but it shouldn't halt execution of the script.

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.