logo

Crreate user programatically in Drupal 8

15
September

Crreate user programatically in Drupal 8
By: Anonymous | Published On: Wed, 09/15/2021 - 22:31

Using following step and method to create user programatically

Must be use this line in above the code

use Drupal\user\Entity\User;

I have added two extra fields in user account that is mentioned below.

Phone - This is text type field. field_phone (Machine name)

Subscribe - This is multiple select type field has machine name as field_subscribe. Following options in

User field edit

user create drupal 8

Now using following code to create user, fields name and their array element you have to use as your structure in user fields.

 

		$subscribe = ['seo' => 'SEO','web' => 'Web Design'];
		$tmp[]['value'] = $subscribe['seo'];
		$tmp[]['value'] = $subscribe['web'];
		
		$user = \Drupal\user\Entity\User::create();
		$user = User::create(array(
		'name' => $name,
		'mail' => $email,
		'pass' => $pass,
		'status' => 1,
		'field_phone' => array(
			'value' => $phone,
		),
		'field_subscribe' => $tmp,
		));

		$user ->addRole('featured');
		$user ->save();
		$uid = $user->id();	

Need Help ?