How to create a user programmatically in Drupal 8 and 9
From time to time you may find that you need to create users that fill in a particular form on your website or create users in bulk from a CSV list. This tutorial will show you how easy it is to create a user. This code can be used almost anywhere, but ideally, place it somewhere sensible! Recently I had to create users after they had filled in a form. So I had to place this code in a custom "Webform Handler" (I will write a tutorial on this soon). Perhaps you can write it in a hook_update_N hook.
Let's start by initializing our User entity.
$user = User::create();
Our $user variable is now a user object that we can use to access methods that will help us easily create a new user in Drupal.
Next, we want to set the status of our new user account. It can either be Blocked or Active.
$user->set('status', 1);
- 0 means blocked.
- 1 means active.
Next, we set the email of the user.
$user->setEmail('ben@example.com');
We can set the username of this account now
$user->setUsername('ben.lamptey');
We can optionally add an additional role to the user account.
$user->addRole('content_editor');
If you have new fields on the user entity, you can also populate those fields. For example, I have "first name" on my user entity. So I get the machine name of this field and populate it like so:
$user->set('field_first_name', 'Benjamin');
Lastly, we want to save our new user
$user->save();
You will now see your new user on the People overview page (/admin/people)