0

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?

6

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 this documentation page https://www.drupal.org/node/2124403

  • 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
3
entity_create('user', [
  'name' => $name,
  'pass' => $password,
  'mail' => $mail,
  'init' => $mail,
  'status' => $status,
  'roles' => $roles
])->save();
  • entity_create() is deprecated in favor of the Entity::create() methods. – mpdonadio Dec 31 '15 at 12:45
  • Yes indeed. But just FYI sometimes the entity type is unknown so entity_* methods are the way to go. But using \Drupal::entityManager()->getStorage($entity_type)->create() does the same trick...although it is no DI-correct solution. – user21641 Dec 31 '15 at 13:20
  • 1
    One can't create an entity without knowing the type, and in your example you gave the type of 'user'. The DI-correct version is just to inject the entity_type.manager service (I don't recall if that's its exact name) and then do what you said re. getStorage($entity_type)->create. btw, entity.manager is also deprecated. drupal.org/node/2549139 – wizonesolutions Jan 2 '16 at 9:05
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');       

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.