How do I create a role programmatically?

What am I doing wrong here?

$role = \Drupal\user\Entity\Role::create(['id' => 'client', 'name' => 'Client']);
  • I update my answer ;-) Dec 15 '15 at 0:46
  • @AdrianCidAlmaguer : I would edit my answer to incorporate those PHP version comments also (5.6, 5.5.9, drupal 8, etc) ... Would make your answer way easier to digest. But of course, that's your choice ... Jul 30 '16 at 15:25
  • @Pierre.Vriens If you want to edit your answer, I don't know which answer, because here there is only one, but if you want edit my answer go ahead. Jul 31 '16 at 3:13

The problem is in the data array change name by label:

$role = \Drupal\user\Entity\Role::create(array('id' => 'client', 'label' => 'Client'));

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
  • Thank you so much, i will try this an let you know. Hmm I find it quite odd that Drupal 8 lets you return array as such but not pass them.... Never mind still learning Drupal 8 cheers!!!
    – Jake Lacey
    Dec 15 '15 at 0:49
  • 1
    Adrian has just separated the lines out so the comments can show you what's going on @Jake, usually the one-liner from your original question would be fine
    – Clive
    Dec 15 '15 at 0:59
  • 1
    Oh I misunderstood, didn't see the first revision of the answer - @Jake, as long as you're using >= php5.4 the short array syntax will work (Drupal doesn't change how php itself works)
    – Clive
    Dec 15 '15 at 1:02
  • 2
    @Adrian Drupal 8 will not work with php <5.6 ;)
    – alexej_d
    Dec 15 '15 at 11:21
  • 1
    @JakeLacey a pleasure and good luck in your projects ;-) Dec 15 '15 at 20:05

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.