How do I create a role programmatically in Drupal 8?
What am I doing wrong here?
$role = \Drupal\user\Entity\Role::create(['id' => 'client', 'name' => 'Client']);
$role->save();
How do I create a role programmatically in Drupal 8?
What am I doing wrong here?
$role = \Drupal\user\Entity\Role::create(['id' => 'client', 'name' => 'Client']);
$role->save();
The problem is in the data array change name by label:
$role = \Drupal\user\Entity\Role::create(array('id' => 'client', 'label' => 'Client'));
$role->save();
Or you can use:
//your data array
$data = array('id' => 'client', 'label' => 'Client');
//creating your role
$role = \Drupal\user\Entity\Role::create($data);
//saving your role
$role->save();
In my case, I wanted to be able to auto-create multiple roles ("clients","managers","salesrep") to work with my custom module.
This is how I auto-create roles programmatically in Drupal 9.
mycustommodule/mycustommodule.module
use Drupal\user\Entity\Role;
function mycustommodule_install() {
//Get all available roles
$get_all_roles=Role::loadMultiple();
//these are the required roles
$required_roles=array("clients","managers","salesrep");
//check if is not already created , create each role
foreach($required_roles as $the_role){
if(!isset($get_all_roles[$the_role])){
$role = Role::create(array('id' => $the_role, 'label' => ucwords($the_role)));
$role->save();
}
}
//
}
Tested passed on Drupal Version 9.4.2