I am creating a Moodle form using the Forms API. I tried to populate a dropdown element in my form using a query.
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'));
}
}
Here's the query:
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));
}
The error that is returned is a general database error. I notice that the example in the Moodle Forms API page uses a global variable, $FORUM_TYPES, where I have used the variable for my query.
Here's the error message:
Coding error detected, it must be fixed by a programmer: PHP catchable fatal error. More information about this error
So my question is -
The problem was that I hadn't converted my query results to an array with a key and value pair.
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'));
}
}
You can achieve the same result without need to convert array in Form function definition(). Because in your query you are selecting only two columns (idnumber and shortname) so you can use get_records_sql_menu function instead of get_records_sql in getMyCourses() function.
get_records_sql_menu will return array with elements already matched in pairs key -> value where first column in select will be key and second -> value.