Enroll user to course

Enroll user to course

by A. Obeid -
Number of replies: 5
Hi, are there intern methods or function to get: - if an user already have a role in this course else enroll him or update his role - Course-id for a course- short-name
Average of ratings: -
In reply to A. Obeid

Re: Enroll user to course

by Darko Miletić -

No. You have to write your own for that. Something like this (untested):


function check_enrol($shortname, $userid, $roleid, $enrolmethod = 'manual') {
    global $DB;
    $user = $DB->get_record('user', array('id' => $userid, 'deleted' => 0), '*', MUST_EXIST);
    $course = $DB->get_record('course', array('shortname' => $shortname), '*', MUST_EXIST);
    $context = context_course::instance($course->id);
    if (!is_enrolled($context, $user)) {
        $enrol = enrol_get_plugin($enrolmethod);
        if ($enrol === null) {
            return false;
        }
        $instances = enrol_get_instances($course->id, true);
        $manualinstance = null;
        foreach ($instances as $instance) {
            if ($instance->name == $enrolmethod) {
                $manualinstance = $instance;
                break;
            }
        }
        if ($manualinstance !== null) {
            $instanceid = $enrol->add_default_instance($course);
            if ($instanceid === null) {
                $instanceid = $enrol->add_instance($course);
            }
            $instance = $DB->get_record('enrol', array('id' => $instanceid));
        }
        $enrol->enrol_user($instance, $userid, $roleid);
    }
    return true;
}


Average of ratings: Useful (5)
In reply to Darko Miletić

Re: Enroll user to course

by A. Obeid -

That is now tested. thx you.


Is there a method to get roleId using role-Name?

In reply to A. Obeid

Re: Enroll user to course

by Darko Miletić -

All roles are stored in role table so to get them by name or short name you can use this:

$roleid = $DB->get_field('role', 'id', array('shortname' => $shortname));




Average of ratings: Useful (2)
In reply to Darko Miletić

Re: Enroll user to course

by A. Obeid -
Hi, it possible to get role-id for course-id and user-id? thx.
In reply to Darko Miletić

Re: Enroll user to course

by Tony Nguyen -
I think

if ($instance->name == $enrolmethod)

should be

if ($instance->enrol == $enrolmethod)

and 

if ($manualinstance !== null)


should be

if ($manualinstance == null)

"name"  field in the  the enrol table have null values. I'm using (2.8)

Average of ratings: Useful (1)