I'm trying to populate a drop down select form with values from a database.
Here is what I have currently.
$modes = Set::combine($this->Setting->find('all', array('conditions' => array('setting_name LIKE' => 'mode_%'))), '{n}.Setting.id','{n}.Setti开发者_高级运维ng.setting_name');
$this->set('modes', $modes);
Then in the view, this is what I have
echo $form->select('current_mode',$modes);
That output
<select name="data[Setting][current_mode]" id="SettingCategoryId">
<option value=""></option>
<option value="2">mode_2</option>
<option value="1">mode_1</option>
<option value="3">mode_3</option>
</select>
The output that I have right now almost work but how can I make the output to be like this?
<select name="data[Setting][current_mode]" id="SettingCategoryId">
<option value="mode_2">Title 2</option>
<option value="mode_1">Title 1</option>
<option value="mode_3">Title 3</option>
</select>
Note:
1. no default option with empty value 2. Option's value isn't the id and titles comes from a "title" field in the tableThanks,
TeeSee http://book.cakephp.org/view/1022/find-list and http://book.cakephp.org/view/1062/displayField.
$settings = $this->Setting->find('list', array(
'conditions' => array('Setting.setting_name LIKE' => 'mode_%'),
'fields' => array('Setting.id', 'Setting.title')
));
$this->set(compact('settings'));
// view
echo $this->Form->input('current_mode', array(
'type' => 'select',
'options' => $settings,
'empty' => false
));
You want to loop through modes and create an option for each mode, like so:
$options = array();
foreach($modes as $mode)
{
$options[$mode] = "Title " . $mode;
}
echo $form->select('current_mode', $options);
You can either put the above logic in your view, or you can do it in your controller, and then set the variable like this:
$this->set("options", $options);
The docs here explain the select element method pretty well:
http://book.cakephp.org/view/1430/select
精彩评论