DropDownList yii 2.0 example

孤街浪徒 提交于 2020-01-23 06:08:57

问题


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?


回答1:


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);
::
?>



回答2:


If you use ActiveForm widget use this:

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



回答3:


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...']) ?>



回答4:


<?= $form->field($model, 'name_of_field')->dropdownList(['1' => 'aaa', '2' => 'bbb'], ['prompt' => '---Select Data---']) ?>


来源:https://stackoverflow.com/questions/26594074/dropdownlist-yii-2-0-example

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!