I am trying to create a dropdown form where the name of a choice is shown to the user, but when they select it, the id of that choice is what is passed as input. Is this possible?

echo form_label('Category');
echo form_dropdown('category_id', $category_options,     
$category[0]->category_name);

Right now this just shows the id of each option.

The reason I have this issue is that my model is taking in the id as that was the only way i could figure out to make it update properly, but the user won't really know what the id stands for and needs the name for a meaningful dropdown menu.

I am getting the ID and the name from the database using a method in my model.

I am new to codeigniter and any help would be appreciated!

2

There are 2 best solutions below

2
Syam On

Your $category_options array should be formatted as key => value (category_id => category_name) pair. For example your array from model should be like this:

$category_options =array(
  1 => 'category1',
  2 => 'category2'
)
echo form_dropdown('category_id', $category_options, '1');

where 1 and 2 are category ids and category1 and category2 are category names. The above code will output

<select name="category_id">
<option value="1" selected="selected">category1</option>
<option value="2">category2</option>
</select>

For more reference check codeigniter form helper documentation : https://ellislab.com/codeigniter/user-guide/helpers/form_helper.html

0
dishrex On

If you want the category ID to be the dropdown value and the category name to be the text that is shown in the dropdown then you could try something like this:

$category_options = array();
foreach($categories->result() as $row){
    $category_options[$row->cat_id] = $row->cat_name;
}

echo form_dropdown('category_id', $category_options);

This just loops through your database results and put them in an associative array where the category id is the key and the category name is the value. Depending on how your model gets the results this might change a little bit.