Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DropDownList yii 2.0 example

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?

like image 631
Aipo Avatar asked Oct 27 '14 18:10

Aipo


4 Answers

If you use ActiveForm widget use this:

<?php 
    $items = ArrayHelper::map(Model::find()->all(), 'id', 'name');
    $form->field($model, 'attribute')->dropDownList($items)
?>
like image 78
olchick Avatar answered Dec 25 '22 12:12

olchick


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);
::
?>
like image 26
Barry Avatar answered Dec 25 '22 10:12

Barry


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...']) ?>
like image 28
Sadia Naseeba Avatar answered Dec 25 '22 11:12

Sadia Naseeba


<?= $form->field($model, 'name_of_field')->dropdownList(['1' => 'aaa', '2' => 'bbb'], ['prompt' => '---Select Data---']) ?>
like image 38
vishuB Avatar answered Dec 25 '22 12:12

vishuB