How to create a user account programmatically in Drupal 8

Public

https://wunderkraut.se/blogg/how-to-create-a-user-account-programmatical...

Get raw version
php
  1. public function submitForm(array &$form, FormStateInterface $form_state) {
  2.  
  3. $language = \Drupal::languageManager()->getCurrentLanguage()->getId();
  4.  
  5. $user = \Drupal\user\Entity\User::create();
  6. $user->setPassword($form_state->getValue('pass'));
  7. $user->enforceIsNew();
  8. $user->setEmail($form_state->getValue('mail'));
  9. $user->setUsername($form_state->getValue('name'));//This username must be unique and accept only a-Z,0-9, - _ @ .
  10. $user->set("init", 'mail');
  11. $user->set("langcode", $language);
  12. $user->set("preferred_langcode", $language);
  13. $user->set("preferred_admin_langcode", $language);
  14. $user->activate();
  15.  
  16. //Save user account
  17. $user->save();
  18.  
  19. // No email verification required; log in user immediately.
  20. _user_mail_notify('register_no_approval_required', $user);
  21. user_login_finalize($user);
  22. drupal_set_message($this->t('Registration successful. You are now logged in.'));
  23. $form_state->setRedirect('');
  24. }