How to make a drop down list in yii2?

前端 未结 12 2001
天命终不由人
天命终不由人 2020-12-04 13:07

How to make a dropdown in yii2 using an activeform and a model? Since all the methods has changed in yii2,how it is done

12条回答
  •  自闭症患者
    2020-12-04 13:58

    This is about generating data, and so is more properly done from the model. Imagine if you ever wanted to change the way data is displayed in the drop-down box, say add a surname or something. You'd have to find every drop-down box and change the arrayHelper. I use a function in my models to return the data for a dropdown, so I don't have to repeat code in views. It also has the advantage that I can specify filter here and have them apply to every dropdown created from this model;

    /* Model Standard.php */
    
    public function getDropdown(){
          return ArrayHelper::map(self::find()->all(), 's_id', 'name'));
    }
    

    You can use this in your view file like this;

    echo $form->field($model, 'attribute')
            ->dropDownList(
                $model->dropDown
            );
    

提交回复
热议问题