DropDownList yii 2.0 example

I am using yii 2.0 Framework. How can I make parameters from my database. I found this, but this is yii 1.1:

<?php echo CHtml::dropDownList('listname', $select, array('M' => 'Male', 'F' => 'Female')); 

I want to pass it to the form:

 <?php $form->dropDownList() ?> 

How can I populate my dropdownlist from my database table?

+7
yii2 yii-components
source share
4 answers

Use yii\helpers\Html , it contains Html::dropDownList() .

 echo Html::dropDownList('listname', $select, ['M'=>'Male', 'F'=>'Female']); 

Check the Yii Framework 2.0 API

controller

 public function actionSomething() { $sexes = ['M'=>'Male', 'F'=>'Female']; $this->render('yourView', ['sexes'=>$sexes]); } 

View

 <?php :: echo Html::dropDownList('listname', $select, $sexes); :: ?> 
+9
source share

If you are using an ActiveForm widget, use this:

 <?php $items = ArrayHelper::map(Model::find()->all(), 'id', 'name'); $form->field($model, 'attribute')->dropDownList($items) ?> 
+12
source share

Yes, if you use the ActiveForm widget, you do not need to change anything in the controller, in the views, in the form, add this where you want the dropdown menu

  use yii\helpers\ArrayHelper; <?php $city = \app\models\City::find()->all(); $listData=ArrayHelper::map($city,'cityId','cityName'); ?> <?= $form->field($model, 'cityId')->dropDownList($listData,['prompt'=>'Choose...']) ?> 
+3
source share
 <?= $form->field($model, 'name_of_field')->dropdownList(['1' => 'aaa', '2' => 'bbb'], ['prompt' => '---Select Data---']) ?> 
+1
source share

All Articles