Craft CMS Asked by Mato on January 16, 2021
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.
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.
Correct answer by James Smith on January 16, 2021
Get help from others!
Recent Questions
Recent Answers
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP