Programmically Creating Roles

By Paulus, 7 March, 2012

I recently wrote a module that required certain roles to be created. My goal was to be able to drop the module in and go, so develop module, install module on live site, and boom goes the dynamite.

The first thing I did was create the function to create the roles:

function _create_roles() {
	$existing_roles = user_roles();
	$new_roles = array('VP of Finance & CFO', 'Finance', 'Senior Vice President and Academic Dean', 'Academic Programs', 'President and CEO', 'President\'s Office', 'Human Resources', 'Supervisor');
	$roles = array();

	foreach($new_roles as $new_role) {
		if(array_search($new_role, $existing_roles) == FALSE) {
			$roles[] = $new_role;
		}
	}

	foreach($roles as $role) {
			db_query('INSERT INTO {role}(name) VALUES(\'%s\')', $role);
	}
}

The only thing I need to do is inject the roles into the database. However, it's best to make sure that I am not adding duplicate roles. On the first line inside the function, I am calling user_roles() which gets an array of all the currently defined roles in the system. I then create an array of roles I wish to add to the system which I iterate through by making sure that each role I want to add does not exist the array of existing roles. Roles that are not in the $existing_roles array gets added to another array which is then iterated through and a query is executed based on each element.