Information for: DEVELOPERS   PARTNERS

Create users programmatically

Fast Track to Drupal 8 Coding – Back to intro
Previous lesson - Add a field to an existing form
Next lesson – Update users programmatically

Lesson Goal

Create a code snippet that can be used as a base to create new users programatically.

Implementation Method

Drupal Version Method
Drupal 7 user_save()
Drupal 8 User::create()

Drupal 7 method

Add the following function to the lotus.module file, being sure to replace <username>, <password>, and <email> with the appopriate values for the user account you want to create:

/**
* Helper function to create a new user.
*/
function create_new_user(){
  $newUser = array(
    'name' => '<username>',
    'pass' => '<password>',  // note: do not md5 the password
    'mail' => '<email>',
    'status' => 1,
    'init' => '<email>',
  );
  // The first parameter is sent blank so a new user is created.
  $user = user_save(null, $newUser);

  drupal_set_message("User with uid " . $user->uid . " saved!\n");
}

Drupal 8 method

Add the following function to the lotus.module file, being sure to replace <username>, <password>, and <email> with the appopriate values for the user account you want to create:

use Drupal\user\Entity\User;
/**
* Helper function to create a new user.
*/
function create_new_user(){
  $user = User::create();

  //Mandatory settings
  $user->setPassword('<password>');
  $user->enforceIsNew();
  $user->setEmail('<email>');

  //This username must be unique and accept only a-Z,0-9, - _ @ .
  $user->setUsername('<username>');

  //Optional settings
  $language = 'en';
  $user->set("init", 'email');
  $user->set("langcode", $language);
  $user->set("preferred_langcode", $language);
  $user->set("preferred_admin_langcode", $language);
  $user->activate();

  //Save user
  $user->save();
  drupal_set_message("User with uid " . $user->id() . " saved!\n");
}

Resources

User::create