5

I need to create users in code specifying password, email and other fields' values.

How can I achieve this?

9

Here you go:

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

// Mandatory.
$user->setPassword('password');
$user->enforceIsNew();
$user->setEmail('email');
$user->setUsername('user_name');

// Optional.
$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->addRole('rid');
$user->activate();

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

Source

  • 3
    User::create() also accepts an associative array for the initial values, too (all entities do). – mpdonadio Apr 9 '16 at 19:21
  • How do i check if the username and email is valid before $user>save()? – Strutsagget Nov 15 '16 at 17:23
  • $violations_user = $user->validate(); if ($violations_user->count() > 0) { $violation = $violations_user[0]; drupal_set_message($violation->getMessage(),'warning'); } – Asy Jan 8 '17 at 15:49
  • I want to write this code in custom module. How do I write this in custom module ? – logeshvaran Jun 6 '17 at 14:55
  • how to check if the user already exist in Drupal? Say if userX is none-existing, create user. – John Rey Tanquinco Aug 23 '18 at 5:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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