I have spent quite some time today, trying to add batch of user accounts intro Drupal8. After all it’s not that difficult, all process is limited to installation of PHP module (that was stripped from Drupal8) and creating new page. Make sure, this page is available only to system administrator!
- Install & enable
PHP filter
- Create new PHP-enabled page (PHP filter)
PHP filter was removed from Drupal8 core.
Below code, defines HTML form and PHP code, that reads the input and store users information. Entries are skipped if given user name is already registered.
Make sure, this page is saved, but UNPUBLISHED! Otherwise, other user will be able to use it and register user accounts!!!
<?php if (!empty($_POST)): echo "Adding users...<br>"; // read textarea $text = trim($_POST['users']); $textAr = explode("\n", $text); $textAr = array_filter($textAr, 'trim'); // remove any extra \r characters left behind $i = 0; foreach ($textAr as $line) { // explode line $parts = preg_split('/\s+/', $line); // check if added $user = user_load_by_name($parts[0]); //$user_id = $user->uid; if(!$user){ $i++; echo " $i $parts[0] $parts[1] <br>"; $language = \Drupal::languageManager()->getCurrentLanguage()->getId(); $user = \Drupal\user\Entity\User::create(); //Mandatory settings $user->setPassword(user_password()); $user->enforceIsNew(); $user->setEmail($parts[1]); $user->setUsername($parts[0]); //Optional settings $user->set("init", $parts[1]); $user->set("langcode", $language); $user->set("preferred_langcode", $language); $user->set("preferred_admin_langcode", $language); $user->activate(); //Save user $res = $user->save(); // create user profile alias: /user/username -> /user/uid $uid = $user->get('uid')->value; $system_path = "/user/$uid"; $path_alias = "/user/$parts[0]"; $path = \Drupal::service('path.alias_storage')->save($system_path, $path_alias, $language); // sent email _user_mail_notify('register_no_approval_required', $user); } else { $uid = $user->get('uid')->value; echo "- $parts[0] already present with uid=$uid!<br>"; } } echo "Added $i users!<br>"; ?> <?php else: ?> <form action="/add_users" method="post"> <p>Provide new users data, one user per line, in this order: username and email (separated by spaces). </p> <textarea name="users" style="width: 400px; height: 200px;"></textarea><br> <input type="submit"> </form> <?php endif; ?>
Voilà!
Inspired by drupal8.ovh & this discussion & this.