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?
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');
}
}
}
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With