0

I try to make an plugin on moodle. i work on moodle 3.0, i already create a moodle form for my plugin, i want to show list of quiz on the form use moodle select element, the form shown when i only show it without a select option. when i try to add an option at the select element use the code from moodle data manipulation API, my form not shown.

this is my code.

public function definition() {
        global $CFG;

        $courses = get_courses('id, fullname, category');
        $arrcourses= array();
        $arrcourses[0] = get_string('choose');
        foreach($courses as $c) {
            if ($c->category !=0){
            $arrcourses[$c->id]=$c->fullname;
            }
        }           
        $view_form = $this->_form; // Don't forget the underscore! 
        $view_form->addElement('select', 'quiz_select', get_string('select_label', 'local_eg'), $arrcourses); // Add elements to your form
        $view_form->setType('quiz', PARAM_INT);    
         $view_form->setType('quiz_select', PARAM_INT);

when i use that my form look like this. select element with list of course

but that select element fill with course list, cause i use the get_course function... then when i try to use get_record_sql function like the code below

class view_form extends moodleform {
    //Add elements to form
    public function definition() {
        global $CFG;

        $courses = get_courses('id, fullname, category');
        $arrcourses= array();
        $arrcourses[0] = get_string('choose');
        foreach($courses as $c) {
            if ($c->category !=0){
            $arrcourses[$c->id]=$c->fullname;
            }
        }
        ////////////////////////////////////////////////////////////////
        // THIS IS THE NEW LINE THAT I ADD TO FILL THE SELECT ELEMENT//
        ///////////////////////////////////////////////////////////////
        $courselist=array();        
        $table= "quiz";
        $result = $DB->get_records_list($table, 'course', array( '2'));

        $view_form = $this->_form; // Don't forget the underscore! 
        $view_form->addElement('select', 'quiz_select', get_string('select_label', 'local_eg'), $arrcourses); // Add elements to your form
        $view_form->setType('quiz', PARAM_INT);    
         $view_form->setType('quiz_select', PARAM_INT);       

I only add 3 new line, after i save and run it, my form is disappear... can anybody help me how to fix that???

1 Answers1

3

Firstly, turn on Debugging (https://docs.moodle.org/en/Debugging) - that would have told you straight away what the problem was.

Secondly, you cannot use global variables of any kind without declaring them in your function. You need to add 'global $DB;' before the first time you use the $DB in your function. In this case, your best bet is to add it to the existing global line, giving 'global $CFG, $DB;'.

davosmith
  • 6,037
  • 2
  • 14
  • 23