digitalist.global // December 23 2015

How to create a user account programmatically in Drupal 8

Here you can read how to create a user programmatically in Drupal 8

Creating a user account is one of the most important task in a web page.

In the next example we are creating a user account with the values given in a form.

public function submitForm(array &$form, FormStateInterface $form_state) {

  $language = \Drupal::languageManager()->getCurrentLanguage()->getId();
  
  $user = \Drupal\user\Entity\User::create();
  $user->setPassword($form_state->getValue('pass'));
  $user->enforceIsNew();
  $user->setEmail($form_state->getValue('mail'));
  $user->setUsername($form_state->getValue('name'));//This username must be unique and accept only a-Z,0-9, - _ @ .
  $user->set("init", 'mail');
  $user->set("langcode", $language);
  $user->set("preferred_langcode", $language);
  $user->set("preferred_admin_langcode", $language);
  $user->activate();
  
  //Save user account
  $user->save();

  // No email verification required; log in user immediately.
  _user_mail_notify('register_no_approval_required', $user);
  user_login_finalize($user);
  drupal_set_message($this->t('Registration successful. You are now logged in.'));
  $form_state->setRedirect('');
}

More from digitalist.global