Yii2下拉列表选择默认选项

8

我正在使用GET方法将cat_id值返回到URL,以便指定我的下拉列表中必须选择哪个项目。 但它没有起作用。

<?= $form->field($model, 'cat_id')->dropDownList(
ArrayHelper::map(DeviceCats::find()
->where(['is_deleted' => 'no'])->all(),'id','title')
,['options' => [$_GET['cat_id'] => ['selected'=>true]]
, 'prompt' => ' -- Select Category --']) ?>

请参考以下链接:http://www.saidur-rahman.com/default-selected-value-in-a-dropdownlist-in-yii/ - Nana Partykar
3个回答

14

最终通过一个难以置信的更改解决了问题。只需将“selected”中的第一个字母改为大写(应该变为“Selected”)。

以下是代码:

<?= $form->field($model, 'cat_id')->dropDownList(
ArrayHelper::map(DeviceCats::find()
->where(['is_deleted' => 'no'])->all(),'id','title')
,['options' => [$_GET['cat_id'] => ['Selected'=>'selected']]
, 'prompt' => ' -- Select Category --']) ?>

10

'选中'应该用大写字母 'S' 写:

'options'=>['72'=>['Selected'=>true]]

4
为什么"selected"一词必须用大写字母"S"来写?这肯定是个bug或者什么奇怪的问题。无论如何,谢谢! - Vasilis Lourdas

1

请确保你的模型具有cat_id属性。在你的控制器中某个位置执行:

$model->cat_id = filter_input_array(INPUT_GET, 'cat_id');

or

    $modelArray = filter_input_array(INPUT_GET, 'nameofmodel');
    $model->cat_id = $modelArray['cat_id'];

如果您真的想像以前那样做,可能需要在其中使用模型的名称。
    <?= $form->field($model, 'cat_id')->dropDownList(ArrayHelper::map(DeviceCats::find()->where(['is_deleted' => 'no'])->all(),'id','title'),['options' => [$_GET['SOMETHIGNHERE']['cat_id'] => ['selected'=>true]], 'prompt' => ' -- Select Category --']) ?>

谢谢Mihai。 实际上,我对数组中现有的值非常确定。 此外,我已经使用了var_dump($_GET),它在第1级别。 - Mojtaba
这是我的观点...它不应该是这样的。你正在费尽心思地让它工作,而且还做错了。相反,你应该将代码移到控制器中。此外,你直接使用PHP全局变量,这是不可取的。 - Mihai P.

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接