Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Moodle user enrollment API

Tags:

api

moodle

I have been asked to create an engine that transform our data on SQL to Moodle data (user, courses, enrollments).

i got stuck at a point where i need to enroll a student programmatically using Moodle API without the need to manipulate the database.

like: enroll_user($courseid, $userid)

does anyone have any input regarding this?

like image 576
Johnny Zghaib Avatar asked Aug 12 '15 13:08

Johnny Zghaib


2 Answers

Something like this

$context = context_course::instance($course->id);
// What role to enrol as?
$studentroleid = $DB->get_field('role', 'id', array('shortname' => 'student'));
// Loop through the students.
foreach ($users as $user) {
    if (!is_enrolled($context, $user->id)) {
        // Not already enrolled so try enrolling them.
        if (!enrol_try_internal_enrol($course->id, $user->id, $studentroleid, time())) {
            // There's a problem.
            throw new moodle_exception('unabletoenrolerrormessage', 'langsourcefile');
        }
    }
}
like image 104
Russell England Avatar answered Sep 22 '22 18:09

Russell England


check this method: check_enrolment($course, $userid, $roleid,'manual');

function check_enrolment($courseid, $userid, $roleid, $enrolmethod = 'manual'){
   
       global $DB;
       $user = $DB->get_record('user', array('id' => $userid, 'deleted' => 0), '*', MUST_EXIST);
       $course = $DB->get_record('course', array('id' => $courseid), '*', 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;
}
like image 24
Arjun Singh Avatar answered Sep 24 '22 18:09

Arjun Singh