0

i want to pass the options as values : here is my code.

  $master_id=array();
        $ret1="select Id from m_tl_mastercourse";
        $result1=get_records_sql($ret1,$limitfrom='', $limitnum='');
        foreach($result1 as $resu){
            $master_id[ ]=$resu->Id;
           
         }
       
    $mform->addElement('select', 'master_id', get_string('selectcourse'), $master_id); 

If i use this means it is looking like below :

<select id="id_master_id" name="master_id">
<option value="0">php01</option>
<option value="1">ios01</option>
<option value="2">and01</option>
<option value="3">java01</option>
<option value="4">python01</option>
<option value="5">yii2</option>

what i want is the exact value will be pass in to the option values. how to get that

Theony
  • 3
  • 1

2 Answers2

1

You're adding to the array as $master_id[ ]=$resu->Id; which by default assigns a numeric index to the array and gives you the next available index number. Assign the key yourself as follows:

  • $master_id[$resu->Id]=$resu->Id;

Note, this assumes that all of your possible options are unique.

Martin Greenaway
  • 545
  • 4
  • 16
1

You can simplify this with the get records menu functions.

https://docs.moodle.org/dev/Data_manipulation_API#get_records_menu

$options = $DB->get_records_menu('m_tl_mastercourse', [], 'id', 'id, name');

$mform->addElement('select', 'master_id', get_string('selectcourse'), $options);

To pass the selected value, you need to pass the value to the form.

https://docs.moodle.org/dev/Form_API#Usage

$formdata = new \stdClass();
$formdata->master_id = 99

$mform = new edit_form();
$mform->set_data($formdata);
$mform->display();
Russell England
  • 9,436
  • 1
  • 27
  • 41