Digitalist Network // 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->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);
  //Save user account

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

More from Digitalist Network