I am trying to create a module which will easily allow me to set up basic sites with specific settings on the fly for a project I'm working on. I am having trouble creating a new user role. I have tried the following code within hook_update_N(), but it doesn't seem to work.

$role = new stdClass(); // create your Class
$role->name = 'editor';

How do I programatically create a new role?

$roles = array('role1','role2','role3');
foreach($roles as $name) {
 $existing_role = user_role_load_by_name($name);
 if (empty($existing_role)) {
  $role = new stdClass();
  $role->name = $name;

I have placed the same snippet in module install file and it is working just fine. You need to enable and then uninstall the module and re-enable it, I hope it will work.

  • I kind of disagree with this approach... If you're planning on setting up new sites from scratch then you should be making a profile, not a module. Also someone should point out why module_update_****() doesn't work - it's because modules utilise a highwater mark for applying updates. Generally they're used for database schema changes (which shouldn't be applied more than once), hence a newly installed module won't run any module_update_****() as the database schema should already be defined and up-to-date, so no updates are required.
    – Pobtastic
    Oct 28 '14 at 13:49

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.