我想productTypes
从数据库中获取一个列表并将它们输出到一个下拉列表,然后该下拉列表将用于 ajax 填充第二个下拉列表。
第 1 步:控制器productTypes
从数据库中获取 第 2 步:控制器将productTypes
对象转换为列表 第 3a 步:输出列表以在视图中进行测试 第 3b 步:使用列表视图填充下拉列表
控制器片段
public function init()
{
$this->dynamicTypes();
$this->render('calculator', array('types' => $this->_types));
}
public function dynamicTypes()
{
$this->_types = CHtml::listData(ProductType::model()->findAll(), 'id', 'type');
}
查看文件片段
<?php
// Step 3a (this works fine)
echo '<pre>';
print_r($types);
echo '</pre>';
// Step 3b - Returns an error
echo $form->dropDownList('productTypes',1, array($types));
?>
<?php $this->endWidget(); ?>
</div>
在步骤 3b 中,我尝试了以下操作:
echo $form->dropDownList('productTypes',1, array($types));
Error Msg: get_class() expects parameter 1 to be object, string given
根据http://www.yiiframework.com/doc/api/1.1/CHtml#dropDownList-detail, dropDownList 方法采用以下参数:
public static string dropDownList(string $name, string $select, array $data, array $htmlOptions=array ( ))
其中第一个参数是一个字符串,表示输入字段的名称。
我做错了什么,我该如何解决?
更新
echo CHtml::dropDownList('productTypes',1, array($types));
似乎可行,但是当我查看视图中的下拉列表时,由于某种原因,下拉列表中有一个 0。出于某种原因,它将选项放入选项组
<select name="productTypes" id="productTypes">
<optgroup label="0">
<option value="1">Scrap</option>
<option value="2">Coin</option>
<option value="3">Bar</option>
</optgroup>
</select>
已解决:已删除array($types)
,仅替换为$types
echo CHtml::dropDownList('productTypes',1, $types);