2

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(); 
Adrian Cid Almaguer
  • 7,815
  • 13
  • 41
  • 63
Jake Lacey
  • 623
  • 7
  • 24

2 Answers2

3

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();
Adrian Cid Almaguer
  • 7,815
  • 13
  • 41
  • 63
0

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

ShapCyber
  • 3,382
  • 2
  • 21
  • 27