7

I am using yii 2.0 Framework. How i can make options from my database. I found this, but it's yii 1.1:

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

I want to pass it to form:

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

How i can fill my dropdownlist from my database table?

Aipo
  • 1,805
  • 3
  • 23
  • 48

4 Answers4

13

If you use ActiveForm widget use this:

<?php 
    $items = ArrayHelper::map(Model::find()->all(), 'id', 'name');
    $form->field($model, 'attribute')->dropDownList($items)
?>
Roman Podlinov
  • 23,806
  • 7
  • 41
  • 60
olchick
  • 711
  • 6
  • 8
11

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

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

Check 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);
::
?>
tony19
  • 125,647
  • 18
  • 229
  • 307
Barry
  • 3,683
  • 1
  • 18
  • 25
  • I am using ActiveForm widget, is it possible to pass parameters there? What is the best way? Create and array in controller, I am out of english examples (: – Aipo Oct 27 '14 at 18:52
  • You can create the array in the controller, but I usually create the array in the view. Are the dropdown values stored in the database or is it just an unstored list of values? – Barry Oct 27 '14 at 18:59
  • Yes, values are stored in database. Can you make an example of how to pass them from controller? – Aipo Oct 27 '14 at 19:03
  • I see in you question that the select values come from a database tabel. Create a model with a method .f.i. `getSexes()` that return the array. – Barry Oct 27 '14 at 19:03
4

Yes if you use ActiveForm widget , u dont have to change anything in the controller , in views, in the form, add this where u want the dropdown

    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...']) ?>
keeg
  • 3,990
  • 8
  • 49
  • 97
Sadia Naseeba
  • 211
  • 2
  • 13
2
<?= $form->field($model, 'name_of_field')->dropdownList(['1' => 'aaa', '2' => 'bbb'], ['prompt' => '---Select Data---']) ?>
vishuB
  • 4,173
  • 5
  • 31
  • 49