1

我在项目中的前任没有将下拉列表值保存在表格中;他们在 html 文件中......这家伙也没有$form->dropdownList()用来创建选择......

当然,我现在在编辑时预选值有很大的问题;因此我将所有更改<select>$form->dropdownList().

但现在我有一个不同的问题,因为

echo $form->dropdownList($model,'location',
        array("Art","Gallery","Bar","Club"));

现在为数据库生成整数值...

我知道我可以像这样设置显示值: array("Art" => "Art").... 但我宁愿避免这种情况 - 有很多视图直接显示值... :(

有没有办法告诉 yii DB 值应该和显示值一样?

4

3 回答 3

6

如果数组值是唯一的(Yii 需要唯一的键),你可以使用...

$data = array("Art","Gallery","Bar","Club");
echo $form->dropdownList($model,'location', array_combine($data, $data));

array_combine将对 listdata 的键和值使用相同的数据。

于 2013-02-06T11:32:37.193 回答
0

您可以按如下方式覆盖小部件的dropDownList方法:CActiveForm

<?php
class ActiveForm extends CActiveForm
{
    public $valuesAsKeys = false;

    public function dropDownList($model,$attribute,$data,$htmlOptions=array())
    {
        if (!$this->valuesAsKeys)
            return parent::dropDownList($model, $attribute, $data, $htmlOptions);

        $newData = array();
        foreach ($data as $value)
            $newData[$value] = $value;
        return parent::dropDownList($model, $attribute, $newData, $htmlOptions);
    }
}

然后像这样使用它:

<?php
$form = $this->beginWidget("application.components.ActiveForm", array(
    'valuesAsKeys' => true,
    // other parameters here
));

// Rendering form's elements here
$this->endWidget();
于 2012-11-15T18:15:30.940 回答
0

Harry B 的回答很好,谢谢!在我的例子中,我想使用自定义选项值并且还包括一个提示,因此为了扩展他的示例,我创建了一个返回键和值数组的方法。keys 数组以'prompt' 开头,'values' 数组以'(select)' 开头,然后我遍历我的数据源并将每个键添加到keys 数组并将每个值添加到values 数组。我的代码有点复杂,涉及正则表达式,但这是基本要点:

// 控制器方法 popupRowListValues($source)
$displayKeys = array('提示');
$displayValues = array('select');

foreach ($source as $key=>$value) {
    $displayKeys[] = $key;
    $displayValues = $价值;
}

// 看法
$displayList = $this->popupRowListValues($source);

echo $form->dropDownListRow($model, $column_name, array_combine(
    $displayList['displayKeys'], $displayList['displayValues']
));
于 2013-07-03T14:33:01.590 回答