function email_registration_unique_username in Email Registration 8
Same name and namespace in other branches
- 6 email_registration.module \email_registration_unique_username()
- 7 email_registration.module \email_registration_unique_username()
Makes the username unique.
Given a starting point for a Drupal username (e.g. the name portion of an email address) return a legal, unique Drupal username. This function is designed to work on the results of the /user/register or /admin/people/create forms which have already called user_validate_name, valid_email_address or a similar function. If your custom code is creating users, you should ensure that the email/name is already validated using something like that.
Parameters
string $name: A name from which to base the final user name. May contain illegal characters; these will be stripped.
int $uid: (optional) Uid to ignore when searching for unique user (e.g. if we update the username after the {users} row is inserted).
Return value
string A unique user name based on $name.
See also
2 calls to email_registration_unique_username()
- EmailRegistrationTestCase::testRegistration in tests/
src/ Functional/ EmailRegistrationTestCase.php - Test various behaviors for anonymous users.
- email_registration_user_insert in ./
email_registration.module - Implements hook_ENTITY_TYPE_insert().
File
- ./
email_registration.module, line 77 - Allows users to register with an email address as their username.
Code
function email_registration_unique_username($name, $uid = 0) {
// Iterate until we find a unique name.
$i = 0;
$database = \Drupal::database();
do {
$new_name = empty($i) ? $name : $name . '_' . $i;
$found = $database
->queryRange("SELECT uid from {users_field_data} WHERE uid <> :uid AND name = :name", 0, 1, [
':uid' => $uid,
':name' => $new_name,
])
->fetchAssoc();
$i++;
} while (!empty($found));
return $new_name;
}