[英]Codeigniter form_dropdown- I want the choices displayed to the user to be different than what is actually inputted to my model
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. 我正在尝试创建一个下拉菜单,其中向用户显示选择的名称,但是当他们选择它时,该选择的ID是作为输入传递的。 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. 现在,这仅显示每个选项的ID。
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. 我遇到这个问题的原因是我的模型采用了id,因为这是我可以找出以使其正确更新的唯一方法,但是用户不会真正知道id代表什么,并且需要a的名称有意义的下拉菜单。
I am getting the ID and the name from the database using a method in my model. 我正在使用模型中的方法从数据库获取ID和名称。
I am new to codeigniter and any help would be appreciated! 我是Codeigniter的新手,任何帮助将不胜感激!
Your $category_options array should be formatted as key => value (category_id => category_name) pair. $ category_options数组的格式应为键=>值(category_id => category_name)对。 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. 其中1和2是类别ID,category1和category2是类别名称。 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 有关更多参考,请检查codeigniter表单帮助程序文档: https : //ellislab.com/codeigniter/user-guide/helpers/form_helper.html
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: 如果您希望类别ID为下拉值,并且类别名称为下拉列表中显示的文本,则可以尝试如下操作:
$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. 这只是循环遍历您的数据库结果,并将它们放入关联数组中,其中类别ID是键,类别名称是值。 Depending on how your model gets the results this might change a little bit.
根据模型获得结果的方式,这可能会有所变化。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.