5

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

How can I achieve this?

10

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
1

Here is my solution I used to migrate old drupal 6 user records to drupal 8. I used entityTypeManager to create user entity.

$values = [
  'name'                     => $data['name'],
  'pass'                     => $data['pass'],
  'mail'                     => $data['mail'],
  'init'                     => $data['init'],
  'status'                   => $data['status'],
  'timezone'                 => $data['timezone_name'],
  'created'                  => $data['created'],
  'access'                   => $data['access'],
  'login'                    => $data['login'],
  'langcode'                 => $data['language'],
  'preferred_langcode'       => $data['language'],
  'preferred_admin_langcode' => $data['language'],
];

if (!empty($data['picture'])) {
  $file_remote_url = $remoteBaseUrl . $data['picture'];
  $file_content = file_get_contents($file_remote_url);
  $file_name = basename($data['picture']);
  $file_uri = 'public://' . $file_name;

  if (!empty($file_content)) {
    $file = file_save_data($file_content, $file_uri, FILE_EXISTS_REPLACE);
    if ($file) {
      $values['user_picture'] = $file->id();
    }
  }
}

/** @var \Drupal\user\Entity\User $entity */
$entity = \Drupal::entityTypeManager()
  ->getStorage('user')
  ->create($values);
$entity->save();

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.