如何让form_dropdown()显示Codeigniter中的选定值?

bla*_*elt 4 codeigniter codeigniter-2

我试图从数据库填充下拉列表.在我的视图文件中,我有以下代码

$batch= $query ['batch']; // I pull this data from a separate model 
echo form_dropdown('shirts', $options, $batch);
Run Code Online (Sandbox Code Playgroud)

现在下拉列表正在填充数据,但问题是我没有得到值 - 页面加载时自动选择"$ batch".有趣的是,如果我回显$ batch,页面中的其他地方显示正确的数据,这意味着$ batch是可以的.

这是我的控制器

function update($id){
$this->load->model('mod_studentprofile');
             $data['query']= $this->mod_studentprofile->student_get($id);
             $data['options']= $this->mod_studentprofile->batchget();

             $data['tab'] = "Update Student Information";
                 $data['main_content']='update_studentprofile';
                 $this->load->view('includes/template',$data);
            }     
Run Code Online (Sandbox Code Playgroud)

这是我的模特

 function batchget() {

      $this->db->select('batchname');
       $records=$this->db->get('batch');

            $data=array();

                        foreach ($records->result() as $row)
                {
                    $data[$row->batchname] = $row->batchname;
                }

            return ($data);
        } 
Run Code Online (Sandbox Code Playgroud)

请你帮我解决这个问题.我希望在页面加载时在下拉列表中自动选择值"$ batch".

提前致谢.

编辑...我的模型为student_get($ id)

  function student_get($id)
    {
        $query=$this->db->get_where('student',array('studentid'=>$id));
        return $query->row_array();
    }      
Run Code Online (Sandbox Code Playgroud)

谢谢 :)

Ant*_*ack 6

我认为可能发生的事情是$ batch中的值可能与下拉列表中的呈现相匹配,但不匹配该特定选项的$ options中的实际键,该选项将是html的value =""部分.

例如...

// this wouldn't select 'foo' as you may be thinking
$options => array('0' => 'foo', '1' => 'bar');
$batch = 'foo';
echo form_dropdown('shirts', $options, $batch);

// this would select foo
$options => array('foo' => 'foo', 'bar' => 'bar');
$batch = 'foo';
echo form_dropdown('shirts', $options, $batch);
Run Code Online (Sandbox Code Playgroud)

编辑以回应OP的评论:

batchget()方法看起来像是以正确的格式返回$ options数组,而student_get()方法返回row_array.看来,在视图中,您将student_get方法返回的其中一个键的值指定为存储在$ batch中的选定值,然后将其作为第三个参数传递给form_dropdown().

这一切似乎都是正确的.只要$ batch的值确实是$ options中的数组键之一,那么form_dropdown()会将其中一个下拉选项设置为已被选中.