1

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?

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.

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

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.

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

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

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

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.