phpdrupalrolesdrupal-8security-roles

How to create a role programmatically in Drupal 8?


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(); 

Solution

  • 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();