How to make a drop down list in yii2?
How to make a dropdown
in yii2
using an activeform
and a model? Since all the methods has changed in yii2
,how it is done in the new one?
It is like
<?php
use yii\helpers\ArrayHelper;
use backend\models\Standard;
?>
<?= Html::activeDropDownList($model, 's_id',
ArrayHelper::map(Standard::find()->all(), 's_id', 'name')) ?>
ArrayHelper in Yii2 replaces the CHtml list data in Yii 1.1.[Please load array data from your controller]
EDIT
Load data from your controller.
Controller
$items = ArrayHelper::map(Standard::find()->all(), 's_id', 'name');
...
return $this->render('your_view',['model'=>$model, 'items'=>$items]);
In View
<?= Html::activeDropDownList($model, 's_id',$items) ?>
It seems you've found your answer already but since you mentioned the active form I'll contribute with one more, even if it differs only ever so slightly.
<?php
$form = ActiveForm::begin();
echo $form->field($model, 'attribute')
->dropDownList(
$items, // Flat array ('id'=>'label')
['prompt'=>''] // options
);
ActiveForm::end();
?>
There are some good solutions above, and mine is just a combination of two (I came here looking for a solution).
@Sarvar Nishonboyev's solution is good because it maintains the creation of the form input label and help-block for error messages.
I went with:
<?php
use yii\helpers\ArrayHelper;
use app\models\Product;
?>
<?=
$form->field($model, 'parent_id')
->dropDownList(
ArrayHelper::map(Product::find()->asArray()->all(), 'parent_id', 'name')
)
?>
Again, full credit to: @Sarvar Nishonboyev's and @ippi