Yii2下拉列表选择值

时间:2019-06-17 19:41:57

标签: yii2

我不知道下拉列表的工作方式。我想从下拉列表中选择选定的值。

我的代码如下:

<?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]) ?>
     <?= $form->field($model1, 'test')->dropDownList($items)->label(false);?>

    <button>Submit</button>
    <?php ActiveForm::end() ?>

其中$items =[‘A’,‘B’,‘C’…‘Z’];

此显示的默认值是“ A”,我想更改此值。

我尝试使用$model1->test,但这不是我选择的值。

谢谢!

3 个答案:

答案 0 :(得分:0)

如果需要提示:

<?= $form->field($model, 'test')->dropDownList($items
    , 'prompt' => ' -- Select Value --']) ?>

如果是其他情况 假设您选择从数组中选择“ B”:

$items =[‘A’,‘B’,‘C’…‘Z’];

“ B”键为1,因此您需要这样做:

<?= $form->field($model, 'test')->dropDownList($items)
,['options' => [1 => ['Selected'=>'selected']]
, 'prompt' => ' -- Select Value --']) ?>

答案 1 :(得分:0)

ActiveForm中,您的模型字段值被选择作为值。
在HTML中,有另一个属性,您可以设置默认值

您可以将HTML中的activeDropDownList()用于给定的模型属性。

Yii2 ActiveForm中的语法:

<?= Html::field($yourModel, 'name_field_db')->dropDownList(
        [items-array of data],
        [options]
    ); ?>

语法HTML:

<?= Html::dropDownList($name, $selection = null, $items = [], $options = []) ?>

数据作为数组

<?= $form->field($model, 'name')->dropDownList(['1' => 'on', '0' => 'off'],['prompt'=>'Select Option']); ?>

通过ArrayHelper::map在下拉列表中显示数据库数据。

    // get fields from database for make itemList
    $yourModels=model::find()->all(); // Query(by Active record or Query Builder or ..)

    $itemList=ArrayHelper::map($yourModels,'filed_id','filed-name');

    echo $form->field($newModel, 'filed-name')->dropDownList($itemList,['prompt'=>'Please select']);

可以用于ActiveForm:$model->field = $model->isNewRecord? 'value' : $model->field;

答案 2 :(得分:0)

使用以下代码,应将ModelName更改为模型类名称,这将起作用。

<?= $form->field($model, 'test')
      ->dropDownList(ArrayHelper::map(app\models\ModelName::find()->all(),'id','test'))
 ?>
相关问题