我被要求创建一个引擎,将我们的SQL数据转换为Moodle数据(用户,课程,注册)。
我陷入困境,我需要使用Moodle API以编程方式注册学生,而无需操作数据库。
喜欢:enroll_user($ courseid,$ userid)
有没有人对此有任何意见?
答案 0 :(得分:5)
像这样的东西
$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');
}
}
}
答案 1 :(得分:2)
检查此方法: 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;
}