Note:

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

Creating roles programmatically: Difference between revisions

From MoodleDocs
Line 5: Line 5:


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]]
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.
The first step is to create an install.php file in the db folder of your plugin.
<pre>/mod/myplugin/db/install.php</pre>
<pre>/mod/myplugin/db/install.php</pre>
Open this new file in your favorite editor and add the following function
<pre>defined('MOODLE_INTERNAL') || die();
function xmldb_local_myplugin_install() {
    global $CFG, $DB, $OUTPUT;
}</pre>
You need to identify the context. So add the following code snippit.
<pre>$context = context_system::instance();</pre>
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 we like to add managers so that they can assign the role to other users. Otherwise, only site administrators can add roles.
<pre>$manager_role = $DB->get_record('role', array('shortname' => 'manager'));
    $mwsync_superadmin_role = $DB->get_record('role', array('shortname' => 'local_myplugin_admin'));</pre>

Revision as of 18:28, 1 March 2013

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 we 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'));