Dropdown In Codeigniter Using Array As Values
I have returned a result_array() in $categories variable and now I want to create a dropdown menu. But if I directly use the variable, all the elements of the array are going to be
Solution 1:
Keys in your $options array are not actual ID's of database rows.
So your $options array looks like this:
Array(
'0' => array('id'=>'10', 'value'=>'someval1'),
'1' => array('id'=>'22', 'value'=>'someval2'),
'2' => array('id'=>'36', 'value'=>'someval3'))
To see this, put print_r($options);
before echo call.
To make real dropdown you should make helper function that looks like this:
functionmy_form_dropdown($name, $result_array){
$options = array();
foreach ($result_arrayas$key => $value){
$options[$value['id']] = $value['value'];
}
return form_dropdown($name, $options);
}
Solution 2:
well since I was getting all the returned rows as array in $categories
Hence a print_r() on $categories gave me the output
Array
(
[0] => Array
(
[id] => 24
[name] => First
)
[1] => Array
(
[id] => 25
[name] => Second
)
[2] => Array
(
[id] => 26
[name] => third
)
)
But I needed something like the code below to make the dropdown work
Array
(
[24] => First
[25] => Second
[26] => third
)
SO I had do modify my code as below
$options = array();
foreach ($categoriesas$category) {
$options[$category['id']] = $category['name'];
}
echo form_dropdown('cat_id', $options);
Hence the HTML generated was as follows which was the markup I desired.
<selectname="category"><optionvalue="24"> First </option><optionvalue="25"> Second </option><optionvalue="26"> Third </option></select>
And it did worked . Thanks for the answers, But after two days of head scratching, I finally did it. Sometimes it is so difficult when u are a beginner.
Solution 3:
you can do
$options = array(
'1' => 'ABC',
'2' => 'NNC'
);
echo form_dropdown('category', $options);
where the key will be the value of the dropdown
Solution 4:
$options = array_combine(
array_column($categories, 'id'),
array_column($categories, 'value')
);
echo form_dropdown('category', $options, '', array('class' => 'form-control'));
Post a Comment for "Dropdown In Codeigniter Using Array As Values"