1

How I can create a user programatically in drupal 8. I am using the following code to generate user registration form.

$account = $this->entityTypeManager->getStorage('user')->create([]);
$form = $this->entityFormBuilder->getForm($account, 'register');

and form_sate values using the following code.

$form_state = (new FormState())->setValues(['name' => 'user1', 'pass' => 'pass']);

Now how can submit this form using the above form_state values?

5

1 Answer 1

1

I think you needn't use the registration form as you have mentioned. You can use the following code to create a new user:

if (!user_load_by_mail('email_id')) {
  $language = \Drupal::languageManager()->getCurrentLanguage()->getId();
  $user = \Drupal\user\Entity\User::create();

  //Mandatory settings
  $user->setPassword('your_password');
  $user->enforceIsNew();
  $user->setEmail('email_id');
  $user->setUsername('user_name'); //This username must be unique and accepts only a-Z,0-9, - _ @ .

  //Optional settings
  $user->set("init", 'email');
  $user->set("langcode", $language);
  $user->set("preferred_langcode", $language);
  $user->set("preferred_admin_langcode", $language);
  //$user->set("setting_name", 'setting_value');
  $user->activate();

  //Save user
  $result = $user->save();
}

You can ensure that an user with same email id doesn't exist using user_load_by_mail(), and then proceed with the user creation.

3
  • Thanks for the answer, here how I can get an error message if a user exist with same email Id in database? Aug 29, 2016 at 7:57
  • I'm not sure how to get the error message, instead you can check if user exists with same email id and then proceed with account creation. I have updated my answer, kindly check it. Accept the answer if it solves your problem.
    – Suresh R
    Aug 29, 2016 at 9:04
  • Actually I was thinking of submitting it as a form so that I can get error messages in "$errors = $form_state->getErrors();". Aug 29, 2016 at 9:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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