Create a user account programmatically in Drupal 8 | Drupal 8

Create a user account programmatically in Drupal 8

Submitted by editor on Sat, 11/14/2015 - 11:32
Question

How to create a user account programmatically in Drupal 8 ?

    Here an example for create a user account programmatically in Drupal 8

 

    $language = \Drupal::languageManager()->getCurrentLanguage()->getId();
    $user = \Drupal\user\Entity\User::create();

//Mandatory settings
    $user->setPassword('password');
    $user->enforceIsNew();
    $user->setEmail('email');
    $user->setUsername('user_name');//This username must be unique and accept 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
    $res = $user->save();

 

Create a new module

Comments

Eyosiyas Tadele (not verified)

Thu, 06/22/2017 - 12:29

I don't wanna write a module and I be able to use drupal functions in my custom php script by including the kernel and bootstap.inc. But when I import  $user = \Drupal\user\Entity\User::create(); it returns 500. Any idea ..?

ugy (not verified)

Wed, 07/19/2017 - 04:51

Is possible to create custom module for admin area? In this case, we want to sync a lot of accounts from another system/web app to our drupal site so we don't need to create manually using "people menu" in admin area.  

Add new comment

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.