2

I am programmatically creating a user and wanted to assign a timezone for the user

I am able to successfully create a user by the following code

$user = \Drupal\user\Entity\User::create();
$user->setPassword('1233455');
$user->enforceIsNew();
$user->setEmail($item['Home - Email']);
$user->setUsername($item['First Name']);

How do I assign the timezone?

1 Answer 1

3

You can use Set method on user Entity like the following:

$user = \Drupal\user\Entity\User::create();
$user->setPassword('1233455');
$user->enforceIsNew();
$user->setEmail($item['Home - Email']);
$user->setUsername($item['First Name']);
//- Set Time Zone to London 
$user->set('timezone','Europe/London');
$user->save();

NOTE : You can set other fields with set method, for example if you can activate the user with $user->set('status',1); or give him administrator role with $user->set('roles',['administrator']); .

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.