0

I am using this code to create user.

  if(user_validate_name('czxc') != ""){
        $user = User::create([
                'name' =>'czxc',    
                'mail' => 'user@gmail.comgczxcdfa',
                'pass' => 'password',
                'status' => 1
             ]);
            $user->save();
            drupal_set_message($user->id());

    }else{
        drupal_set_message('Already exist user'); 
    }
   This code works only one time for me.
2

The user_validate_name function from Drupal only verifies the syntax of the given name.

It does not validate whether the username exists or not.

You could replace the function call, like so:

$uids = \Drupal::entityQuery('user')
  ->condition('name', 'czxc')
  ->execute();
if (count($uids) > 0) {
  $user = User::create([
    'name' =>'czxc',
    'mail' => 'user@gmail.comgczxcdfa',
    'pass' => 'password',
    'status' => 1
  ]);
  $user->save();
  drupal_set_message($user->id());

} else {
  drupal_set_message('Already exist user');
}
| improve this answer | |
  • Could entityTypeManager service be used to loadByProperties the account name? – Kevin Oct 3 '18 at 16:02
  • 1
    @Kevin Same thing as I mentioned on the other answer - probably no point loading the full entity when you just need to know if it exists – Clive Oct 3 '18 at 16:03
  • @Kevin, yes, loadByProperties loads the whole user entity, then you can get the name. – Cesar Moore Oct 10 '18 at 23:10

Not the answer you're looking for? Browse other questions tagged or ask your own question.