Yii Framework: 从 model 中生成 select option

本文介绍如何利用Yii框架的CHtml帮助类中的listData()和dropDownList()函数生成下拉选项,以实现用户友好的选择功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 
在 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>

其它几个参数不会用,等段时间在研究 更新

public static string dropDownList(string $name, string $select, array $data, array $htmlOptions=array ( ))
$namestringthe input name
$selectstringthe selected value
$dataarraydata 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.
$htmlOptionsarrayadditional 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}stringthe generated drop down list
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值