Note:

If you want to create a new page for developers, you should create it on the Moodle Developer Resource site.

Creating roles programmatically

From MoodleDocs
Revision as of 12:34, 10 November 2013 by Petr Škoda (škoďák) (talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Warning: This page is no longer in use. The information contained on the page should NOT be seen as relevant or reliable.

You may find that the default roles do not answer the needs of your plugin. In that case, you want to create a role programmatically.

Setup

We will use a plugin called myplugin.

It is best to create capabilities for your plugin first as they will be used to create the role. You can also use default Moodle capabilities. For more information, please refer to Roles#Programming_Interface

install.php

The first step is to create an install.php file in the db folder of your plugin.

/mod/myplugin/db/install.php

Open this new file in your favorite editor and add the following function

defined('MOODLE_INTERNAL') || die();

function xmldb_local_myplugin_install() {
    global $CFG, $DB, $OUTPUT;

}

You need to identify the context. So add the following code snippit.

$context = context_system::instance();

Now lets find out if the role already exists. We will also need the manager role in order to add managers to the role. This is not required, but I like to add managers so that they can assign the role to other users. Otherwise, only site administrators can add roles.

$manager_role = $DB->get_record('role', array('shortname' => 'manager'));
    $mwsync_superadmin_role = $DB->get_record('role', array('shortname' => 'local_myplugin_admin'));