Yii2 to create select options in a form with dropDownList function

Would you like to create select options in a form with Yii Framework 2.0? In this tutorial I will explain to you how you can create select options in a form and how you can extract options from a database.

Open your Model's form and add new field called option.

Next, open your view file and add this code:

<?= $form->field($model, 'option)->dropDownList(array('1'=>First option','2'=>'Second Option')) ?>

I have created a simple script which can extract the options from database.

In my controller i have added this code:

$categories = Categories::findBySql('SELECT * FROM categories')->all();
return $this->render('publish-video', [
'model' => $model,
'categories' => $categories,

And in my view file I have added this code:

$id = '';
$name = '';
foreach($categories as $category):
$id[] = $category->id;
$name[] = $category->name;
$result = array_combine($id, $name);
$result = array("0"=>"No categories found");
$form->field($model, 'category')->dropDownList($result)

In the video bellow you can see the results of this script:

Leave a Comment