Skip to content

How to make a drop down list in yii2?

Last updated on February 10, 2018

In this tutorial, I would like to show you making the dropdown list in yii2 using different data sources like static array data and database table modal data.

First I would like to share basic syntax – here you go…

Yii2 DropDownList syntax – active field style

echo $form->field($model, 'name_field')->dropDownList(
        [items],
        [options]
    );

Yii2 DropDownList syntax – active form style

echo Html::field($model, 'name_field')->dropDownList(
        [items],
        [options]
    );

Both style are almost same , but active field style is good because it maintains the creation of the form input label and help-block for error messages where active form style generate only dropdown.

DropDownList with array data

field($model, 'name')->dropDownList(['1' => 'Yes', '0' => 'No'],['prompt'=>'Select Option']);
?>

DropDownList with model data

Using below code snippet you can display the database table column’s data in the dropdownList via modal.

all();
 
// default selected country , here 10 is country id
$countries->country_id = 10;
 
// convert $country modal result to array format using ArrayHelper's map() method. 
$countryList=ArrayHelper::map($countries,'country_id','name');
 
// this will generate dropdownList with given array of data.
echo $form->field($model, 'name')->dropDownList($countryList,['prompt'=>'Please select country']);
 
?>

Here we used use yii\helpers\ArrayHelper. ArrayHelper has many use full functions which could be used to process arrays. map() is the one, we are going to use here this function which will help to make a map ( of key-value pairs) from a multidimensional array or an array of objects.

Generating dropdownlist with option groups.

Below is the simple example on creating dropdownList with option groups

$countries = array(
        'Asia'=>array(
            'russia'=>'Russia',
            'india'=>'India',
        ),
        'Africa'=>array(
            'kenya'=>'Kenya',
            'zimbabwe'=>'Zimbabwe',
        ),
    )
 
echo $form->field($model, 'country_id')->dropDownList($countries);
0 0 votes
Article Rating
Subscribe
Notify of
guest

3 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments