2

I know that I can programmatically create a user using the following code, in Drupal 7.

$new_user = array(
  'name' => $name,
  'pass' => $sifra, // note: do not md5 the password
  'mail' => $email,
  'status' => 1,
  'init' => $email,
  'roles' => array(
    DRUPAL_AUTHENTICATED_RID => 'authenticated user',
    3 => 'custom role',
  ),
);

// The first parameter is sent blank so a new user is created.
user_save('', $new_user);

What is the equivalent code in Drupal 8?

0

5 Answers 5

7

You should use the suiting entity class. In case of a user it would be Drupal\user\Entity\Userand you can use it as follows:

Drupal\user\Entity\User::create([
  'name' => $name,
  'pass' => $sifra,
  …
])->save();

Make sure to check the Create section on Working with the Entity API.

2
  • can I use this code in custom module ? Commented Jun 6, 2017 at 14:42
  • Sure, this is standard code and therefor not protected by any copyright ;)
    – alexej_d
    Commented Jun 6, 2017 at 15:38
14

For Drupal 8, the code to create a user entity is the following one.

$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();

The code can be found on Create a user account programmatically in Drupal 8.

1
  • 3
    User::create() also accepts an associative array for the initial values, too (all entities do).
    – mpdonadio
    Commented Apr 9, 2016 at 19:21
3

For beyond Drupal 8.3.

<?php

use Drupal\user\Entity\User;

// Create user object.
$user = User::create();

//Mandatory settings
$user->setPassword("password");
$user->enforceIsNew();
$user->setEmail("email");
$user->setUsername("username"); //This username must be unique and accept only a-Z,0-9, - _ @ .
$user->addRole('role_name'); //E.g: authenticated

To Set custom field values

$user->set("field_machine_name", 'value');       
1
  • 1
    This still requires a $user->save(); Commented Mar 20, 2020 at 3:01
1

This is the code I used to migrate old Drupal 6 user records to Drupal 8. I used the entity_type.manager service to create user entities.

$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();
1

For Drupal 8 I use this code to create a user with a predefined uid and an already hashed password from Drupal 7:

        $user = User::create(array(
          'uid' => $data[0],
          'name' => $data[1],
          'pass' => $data[2],
          'mail' => $data[3],
          'status' => $data[4],
          'access' => $data[6],
          'login' => $data[7],
          'timezone' => $data[8],
          'langcode' => $data[9],
          'preferred_langcode' => $data[9],
          'preferred_admin_langcode' => $data[9],
          'init' => $data[10],
        ));
        $user->created = $data[5];
        $roles = explode(",", $data[11]);
        foreach ($roles as $role) {
          switch ($role) {
            case 3:
              $user->addRole('administrator');
              break;

            case 4:
              $user->addRole('contributeur');
              break;

            case 6:
              $user->addRole('admin_m2');
              break;
          }
        }
        // Save user account.
        $user->save();

        $database = \Drupal::database();
        // Dirty overwrite of the re-hashed hash.
        $database->merge('users_field_data')
          ->fields(['pass' => 'YOUR_D7_HASH_HERE'])
          ->keys(array('uid' => $data[0]))
          ->execute();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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