2

I want to programmatically create new roles in Drupal 8. I found this code in this post.

//your data array
$data = array('id' => 'client', 'label' => 'Client');
//creating your role
$role = \Drupal\user\Entity\Role::create($data);
//saving your role
$role->save();

But I don't know where I should put it, in which file, which folder? And how do I run it?

  • 1
    when you need to create the roles? – Adrian Cid Almaguer Jan 23 '17 at 15:48
  • I have a list of roles and i want to create them, When ? Now – usethe23 Jan 23 '17 at 15:50
  • I don't want to do anything else, just create the roles – usethe23 Jan 23 '17 at 15:51
  • 1
    You can do it when a module gets installed with hook_install, or you can choose to put it in a hook_update_n function. It's up to you. Don't "just" run code once that changes the db, because you will lose installability. – Ruben Beekman Jan 23 '17 at 15:55
3

You have many place to create your roles, a simple way for you (As you says that you don't know nothing about Drupal) can be create a custom page (read the post) if you follow the example in the myPage() function you can go trough your list of roles and create each role in a loop, something like this;

public function myPage() {
...
  /* Read your roles
   * $my_roles[0]['id'] = 'client';
   * $my_roles[0]['label'] = 'My Client';
   */
  for ($i = 0; $i < count($my_roles); $i++) {
    //your data array
    $data = array('id' => $my_roles[$i]['id'], 'label' => $my_roles[$i]['label']);
    //creating your role
    $role = \Drupal\user\Entity\Role::create($data);
    //saving your role
    $role->save();
  }
...
}

And if you go to your page you will create your roles.

EDIT: As Kevin says is better in other places like the hook_install()

Follow the steps to create a module and implement the hook_install() (Read at the end of the page how to do it)

Inside the hook implementation you will put the code:

/**
 * Implements hook_install().
 */
function YOUR_MODULE_install() {
    /* Read your roles
     * $my_roles[0]['id'] = 'client';
     * $my_roles[0]['label'] = 'My Client';
     */
    for ($i = 0; $i < count($my_roles); $i++) {
      //your data array
      $data = array('id' => $my_roles[$i]['id'], 'label' => $my_roles[$i]['label']);
      //creating your role
      $role = \Drupal\user\Entity\Role::create($data);
      //saving your role
      $role->save();
    }
}

To create your roles you only need install your module.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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