Yii2下拉列表默认值

5
在yii2中,我有一个下拉列表:
<?= $form->field($model, 'Körperschaft')->dropDownList(['a' => 'Item A', 'b' => 'Item B', 'c' => 'Item C'])?>

我该如何将“项目B”设置为默认值?
4个回答

8

试试这个

<?= $form->field($model, 'Körperschaft')->dropDownList(['a' => 'Item A', 'b' => 'Item B', 'c' => 'Item C'], ['options'=>['b'=>['Selected'=>true]]])?>

4

我明白了!解决方案是在控制器中编写:

public function actionCreate()
{


    $model->Körperschaft='b';

0
您可能需要将其放在负责保存的行之后,否则,即使用户选择了不同的值,该值也永远不会更改。以下是一个示例:
    public function actionCreate(){
     //Something you want to do before saving
      if ($model->load(Yii::$app->request->post()) && $model->save()) {
       //Something you do after saving before redirecting
        return $this->redirect(['your-prefered-page']);
    }
     // Some other lines of code
     $model->Körperschaft='b';
     return $this->render('create', [
                'model' => $model,
    ]);
 }

我认为这可以帮助。


0
你可以使用以下代码。这里,b将作为默认值出现。
<?= Html::dropDownList('modelfield', null, ['1' => 'a', '2' => 'b', '3' => 'c'], [ 'class'=>'form-control','prompt' => 'Select Rating', 'options' => [ 2 => ['Selected'=>'selected']] ]); 
            ?>

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