How To Populate Dropdownlist

We did the below to populate a drop down

<code><?php echo $form->dropDownList($model, ‘country_id’, GxHtml::listDataEx(Country::model()->findAllAttributes(null, true))); ?></code>

But how to do it in Yii2?

I have a state table and country table as in the below

State(id,name, country_id)

country(id,name)

I want to display a country drop down in the state/create form. (I know the way of doing in Yii 1.X version, but I am trying to find in Yii2 style. ) It would be great if that is ajaxdropdown?

Did any body did it already?

Thanks in advance.

You can use new helper ArrayHelper, it’s really useful.

For example,




$data = Country::find()

    ->select(['id', 'name'])

    ->asArray()

    ->all();


return \yii\helpers\ArrayHelper::map($data, 'id', 'name');



ORey,

Thank you very much for a quick answer. That is working for me.

This is the most optimized way to get populate a dropdownlist?


<?= $form->field( $model, 'source_id')->dropDownList(

ArrayHelper::map( Source::find()->all(), 'id', 'name' ),

[ 'prompt' => '' ]

) ?>

how can i emulate the old findallBySql with yii2??

Country::findBySql(‘SELECT * FROM country’)->all();