Yii Framework: 从 model 中生成 select option
在 Yii framework 的论坛有人问,如何用 yii 的方式来生成一个下拉选项。 在这里就介绍下方法。 首 先我们可以通过 CHtml 帮助类中的 listData() 函数来帮助我们生成一个下拉选项所需要的数
在 Yii framework 的论坛有人问,如何用 yii 的方式来生成一个下拉选项。 在这里就介绍下方法。
首 先我们可以通过 CHtml 帮助类中的 listData() 函数来帮助我们生成一个下拉选项所需要的数组。然后再通过同样是 CHtml 帮助类中的 dropDownList() 或者 activeDropDownList() 函数来生成我们需要的下拉选项。
比如我们现在有一个 User Model,包含 id, username, password 等属性, 现在我们想生成一个 id 为 key, username 为 value 的下拉选项, 我们可以这样操作:
// controller file $users = User::model()->findAll(); //view file <p><?php echo CHtml::dropDownList( "user", null, CHtml::listData($users, "id", "username")); ?></p>
我们还可以参考手册来进行更复杂的操作。
我测试使用这段时,在controller 中加入参数不行 直接在view页面使用$user变量,这样正常显示。
<?php $complain = Complain::model()->findAll();
?>
<p><?php echo CHtml::dropDownList(
“category_id”, //select name以及id
68, //默认值,
CHtml::listData($complain, “id”, “c_title”)); $complain是一个多维数组, id 是complain的id号做option value , c_title是列表显示值,显示名称
?></p>
其它几个参数不会用,等段时间在研究 更新
dropDownList() methodpublic static string dropDownList(string $name, string $select, array $data, array $htmlOptions=array ( )) | ||
$name | string | the input name |
$select | string | the selected value |
$data | array | data for generating the list options (value=>display). You may use listData to generate this data. Please refer to listOptions on how this data is used to generate the list options. Note, the values and labels will be automatically HTML-encoded by this method. |
$htmlOptions | array | additional HTML attributes. Besides normal HTML attributes, a few special attributes are recognized. See
clientChange and
tag for more details. In addition, the following options are also supported specifically for
dropdown list:
|
{return} | string | the generated drop down list |
声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。
- 上一篇: php中foreach用法
- 下一篇: 项目优化总结