Reputation: 1816
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 displayed. However I just want to display the name and keep its id as value. How do i do it?
$options = $categories;
echo form_dropdown('category', $options);
I want something like
<select name="category">
<option value="1"> ABC </option>
.....
<option value="10"> NNNC </option>
</select>
Upvotes: 0
Views: 9329
Reputation: 21
$options = array_combine(
array_column($categories, 'id'),
array_column($categories, 'value')
);
echo form_dropdown('category', $options, '', array('class' => 'form-control'));
Upvotes: 0
Reputation: 1816
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 ($categories as $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.
<select name="category">
<option value="24"> First </option>
<option value="25"> Second </option>
<option value="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.
Upvotes: 1
Reputation: 1262
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:
function my_form_dropdown($name, $result_array){
$options = array();
foreach ($result_array as $key => $value){
$options[$value['id']] = $value['value'];
}
return form_dropdown($name, $options);
}
Upvotes: 5
Reputation: 4527
you can do
$options = array(
'1' => 'ABC',
'2' => 'NNC'
);
echo form_dropdown('category', $options);
where the key will be the value of the dropdown
Upvotes: 0