How to get form_dropdown() show the selected value in Codeigniter?
I am trying to populate a dropdown list from database. In my view file I have the following code
$batch= $query ['batch']; // I pull this data from a separate model
echo form_dropdown('shirts', $options, $batch);
Now the drop down list is populating data fine but the problem is I don't get the value-"$batch" automatically selected when the page loads. Interestingly if I echo $batch, elsewhere in the page it shows the correct data, which means $batch is okay.
Here is my Controller
function update($id){
$this->load->model('mod_studentprofile');
$data['query']= $this->mod_studentprofile->student_get($id);
$da开发者_StackOverflowta['options']= $this->mod_studentprofile->batchget();
$data['tab'] = "Update Student Information";
$data['main_content']='update_studentprofile';
$this->load->view('includes/template',$data);
}
And here is my model
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);
}
Would you please kindly help me to solve this problem. I want to have the value- "$batch" automatically selected in the dropdown list when the page loads.
Thanks in Advance.
EDit... my Model for student_get($id)
function student_get($id)
{
$query=$this->db->get_where('student',array('studentid'=>$id));
return $query->row_array();
}
Thanks :)
I think that what's probably happening is that the value in $batch may be matching what's rendering in the dropdown but not the actual key in $options for that particular option which would be the value="" portion of the html.
for example...
// 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);
Edit in response to OP's comment:
The batchget() method looks like it returns your $options array in the proper format and your student_get() method is returning a row_array. It appears that in the view you're assigning the value of one of the keys returned by the student_get method to be the selected value stored in $batch which is then passed in as the third argument to form_dropdown().
This all appears to be correct. As long as the value of $batch is indeed one of the array keys that is in $options then form_dropdown() will set one of the dropdown options as having been selected.
Debug stuff.
var_dump()
$options
, var_dump() $batch
, look at the two and see where you went wrong.
The third option must be the value of the key, not the value of the label.
Anthony Jack is probably right.
精彩评论