Event USER_ENROLLED : how to catch the real roleid ?

Re: Event USER_ENROLLED : how to catch the real roleid ?

by Artur Welp -
Number of replies: 0

I had this problem today. More than one year after, so i think it is no longer useful.


It is not possible get the user role in the event: core\event\user_enrolment_created, because Moodle deal with enrolment_created and core\event\role_assigned in different ways.


First he create the enrolment, this trigger an event core\event\user_enrolment_created at this point the user role is not defined yet.

Than he assign the role to the user, this trigger an event core\event\role_assigned. Probably this is the event you want.


This can be seen in the file lib/enrollib.php from line 1321 onward.

//Line 1320 - File lib/enrollib.php
if ($inserted) {
// Trigger event.
$event = \core\event\user_enrolment_created::create(
array(
'objectid' => $ue->id,
'courseid' => $courseid,
'context' => $context,
'relateduserid' => $ue->userid,
'other' => array('enrol' => $name)
)
);
$event->trigger();
// Check if course contacts cache needs to be cleared.
require_once($CFG->libdir . '/coursecatlib.php');
coursecat::user_enrolment_changed($courseid, $ue->userid,
$ue->status, $ue->timestart, $ue->timeend);
}

if ($roleid) {
// this must be done after the enrolment event so that the role_assigned event is triggered afterwards
if ($this->roles_protected()) {
role_assign($roleid, $userid, $context->id, 'enrol_'.$name, $instance->id);
} else {
role_assign($roleid, $userid, $context->id);
}
}


So this is my code to get the user role:

public static function my_plugin_role_assigned(core\event\role_assigned $enrolment_data){        
global $DB;

//strange var name, better change it
$enrolment_data_data = $enrolment_data->get_data();
$snapshotid = $enrolment_data->get_data()['other']['id'];
$snapshot = $enrolment_data->get_record_snapshot('role_assignments', $snapshotid);

$roleid = $snapshot->roleid;
$rolename = $DB->get_records_sql("SELECT shortname from {role} WHERE id = ?", array($roleid));
$rolename = array_pop($rolename);
$rolename = $rolename->shortname;

if($rolename == 'editingteacher'){
//My stuff
}

}

Tip: Instead of use roleid, use role shortname, because if you export something to other Moodle installation, the roleid may be different.


Average of ratings: Useful (2)