牛骨文教育服务平台(让学习变的简单)
博文笔记

Yii Framework: 从 model 中生成 select option

创建时间:2011-08-04 投稿人: 浏览次数:2122
  在 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() method
public 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:

  • encode: boolean, specifies whether to encode the values. Defaults to true. This option has been available since version 1.0.5.
  • prompt: string, specifies the prompt text shown as the first list option. Its value is empty.
  • empty: string, specifies the text corresponding to empty selection. Its value is empty. Starting from version 1.0.10, the ‘empty’ option can also be an array of value-label pairs. Each pair will be used to render a list option at the beginning.
  • options: array, specifies additional attributes for each OPTION tag. The array keys must be the option values, and the array values are the extra OPTION tag attributes in the name-value pairs. For example,
        array(
            "value1"=>array("disabled"=>true, "label"=>"value 1"),
            "value2"=>array("label"=>"value 2"),
        );

    This option has been available since version 1.0.3.

{return} string the generated drop down list
声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。