I have a front-end user registration form that generates a username automatically based on the first and last name inputs. This works as intended but on the off chance that two people have the same name, a check needs to be run on submit to see if the username already exists in the system. I'm currently utilizing {{ actionInput('users/save-user') }}
to handle the form submit. I'm looking for a way to run a check before the action users/save-user
returns the defualt duplicate username error. I've created a module to listen for the save event but it doesn't appear to be firing as intended. Within the module's init()
function I'm running:
Event::on(
User::class,
User::EVENT_BEFORE_SAVE,
function (ModelEvent $event) {
$loginName = $this->request->getRequiredBodyParam('username');
if($user = Craft::$app->getUsers()->getUserByUsernameOrEmail($loginName)){
// Change the username to username-(duplicateCount+1)
// Create New User
} // else {
// Create New User
// }
}
);
using use craft\elements\User;
Disclaimer: I'm a novice when it comes to modules/plugins/controllers so any advice would be greatly appreciated. Thanks!
\Craft::dd($loginName)
to see if the hook is actually firing. In this case it might just be down to a simple logic error.die();
within the event. The event fires correctly when a new user is created but fails to fire when loginName is a duplicate. Craft's default duplicate check appears to preventEVENT_BEFORE_SAVE
from firing.EVENT_BEFORE_VALIDATE
instead!