使用查询填充 Moodle 表单中的 select 元素

Using a query to populate a select element in a Moodle form

我正在使用 Forms API 创建 Moodle 表单。我尝试使用查询在我的表单中填充下拉元素。

class my_form extends moodleform {

    function definition() {
        $mform =& $this->_form;

        $mform->addElement('html', '<h2>' . get_string('header', 'local_data')  . '</h2>');

        global $USER;
        $userid = $USER->id;
        $myCourseIds = getMyCourses($userid);

        $mform->addElement('select', 'courseid', get_string('courseid', 'local_data'), $myCourseIds);


        $this->add_action_buttons(true, get_string('send', 'local_data'));
    }

}

查询如下:

function getMyCourses($userid) {
    global $DB;

    $sql = 'SELECT c.idnumber, c.shortname
            FROM {role_assignments} ra, {user} u, {course} c, {context} cxt, {attendance_sessions} ass, {attendance} att
            WHERE ra.userid = u.id
            AND ra.contextid = cxt.id
            and att.id = ass.attendanceid
            and c.id = att.course
            AND cxt.instanceid = c.id
            AND (roleid =12 OR roleid=3)
            and u.id = ?';

    return $DB->get_records_sql($sql, array($userid));
}

返回的错误是一般数据库错误。我注意到 Moodle Forms API 页面中的示例使用了全局变量 $FORUM_TYPES,我在其中将变量用于我的查询。

错误信息如下:

Coding error detected, it must be fixed by a programmer: PHP catchable fatal error. More information about this error

所以我的问题是 -

问题是我没有将查询结果转换为具有键值对的数组。

class my_form extends moodleform {

    function definition() {
        $mform =& $this->_form;

        $mform->addElement('html', '<h2>' . get_string('header', 'local_data')  . '</h2>');

        global $USER;
        $userid = $USER->id;
        $myCourseIds = array();
        $selectArray = array();
        $myCourseIds = getMyCourses($userid);
      // push query results into selectArray as key, value
        foreach($myCourseIds as $myCourseId) {
            $key = $myCourseId->idnumber;
            $value = $myCourseId->shortname;
            $selectArray[$key] = $value;
        }

        $mform->addElement('select', 'courseid', get_string('courseid', 'local_data'), $selectArray);    

        $this->add_action_buttons(true, get_string('send', 'local_data'));
    }

}

无需在 Form 函数 definition() 中转换数组即可获得相同的结果。 因为在您的查询中您只 selecting 两列(idnumber 和 shortname)所以您可以使用 get_records_sql_menu 函数而不是 get_records_sqlgetMyCourses() 函数中。

get_records_sql_menu 将 return 数组,其元素已成对匹配键 -> 值,其中 select 中的第一列将是键和第二 -> 值。

Moodle Docs Reference