Yii Framework 2.0 Tutorial

Yii Framework 2.0 DropDownList

"Do you know How to display the data in drop down list?" This tutorial will help you to display the array data or model data in drop down list in different way.

Default DropDownList

Yii2.0 default dropdownlist syntaxt.

<?php echo $form->field($model, 'name[]')->dropDownList(['a' => 'Item A', 'b' => 'Item B', 'c' => 'Item C']); ?>
Yii2.0 default dropdownlist syntaxt with prompt text like default text value.

<php echo $form->field($model, 'name[]')->dropDownList($listData, 
						['prompt'=>'Select...']);>
Using below code, we can display the database value (via model) in dropdownlist of yii2.0 framework.

<?php 
//use app\models\Country;
$countries=Country::find()->all();

//use yii\helpers\ArrayHelper;
$listData=ArrayHelper::map($countries,'code','name');

echo $form->field($model, 'name')->dropDownList(
								$listData, 
								['prompt'=>'Select...']);
?>

Default Selection DropDownList Yii2

Using below code, we can set the default value for dropdownlist of yii2.0 framework. When we create the new entry for country population, we will try to set the value to auto select of dropDownList. During the updation it will fetch the country code automatically from db record. Please see the below code to get it.

Controller Code


<??php
...................
public function actionCreate()
{
	$model = new Population();
	// Default Selection for country code
	$model->country='IN';
	if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->code]);
	} else {
		return $this->render('create', [
			'model' => $model,
		]);
	}
}
public function actionUpdate($id)
{
	$model = $this->findModel($id);
	return $this->render('update', [
		'model' => $model,
    ]);
}
...................
?>

Create/Update Form Code


<??php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
use yii\helpers\ArrayHelper;
?>

<?div class="population-form">
    <??php $form = ActiveForm::begin(); ?>
	...................
	<??php
		//$model->name='IN';
		$listData=ArrayHelper::map($countries,'code','name');
		echo $form->field($model, 'name')->dropDownList($listData, ['prompt'=>'Choose...']);
	?>
	...................
    <??php ActiveForm::end(); ?>
<?/div>
  • Robert

    How to set default value selected in drop-down list?

  • Victor Okrobodo

    Can you please provide code on how to display dropDownList with Model DB data and select a default value. For example how can I display a drop down list of all countries in my database and show Denmark preselected?

    • m bala

      Do you want this ?

      <?php $model->name=’RU’;
      $countries=Country::find()->all();
      $listData=ArrayHelper::map($countries,’code’,’name’);
      echo $form->field($model, ‘name’)->dropDownList($listData, [‘prompt’=>’Choose…’]);

      ?>

      • Victor Okrobodo

        Yes… But take it a step further. How can you display a default country from the returned list. Currently, I achieve that using Jquery. Something like this
        $(‘#country’).val(5)…to set the 5th element as the default option to be displayed on the dropdown list. Is there a way to achieve this in Yii2 without resorting to jquery?

        • m bala

          I could not understand your query. sorry

  • ignacio aular

    Hello, please how can I using ucfirst to save my data in Yii2?

  • Hoanguyen

    hello, how can I add different class for each option tag? thanks

  • Arjen Meijer

    How do I expand the DropDownList With Model (DB) Data example
    if the selected value is taken from a daughter table?

    That is, select an id in the viaTable, but present the name of attribute in the ‘endTable’.

    • m bala

      More details pls

      • Arjen Meijer

        $gisv = Yii::$app->db->createCommand(‘SELECT g.gebeurtenis_id as gebeurtenis_id, g.samenvatting as samenvatting
        FROM `tbl_gebeurtenisinspelvorm` AS gisv
        LEFT JOIN tbl_gebeurtenis g ON gisv.gebeurtenis_id = g.gebeurtenis_id
        WHERE spelvorm_id =4′);
        $geb = $gisv->queryAll();
        $keuzeData=ArrayHelper::map($geb,’gebeurtenis_id’, ‘samenvatting’);
        echo $form->field($model, ‘gebeurtenisinspelvorm_id’)->dropDownList($keuzeData,[‘prompt’=>’Kies een gebeurtenis’]);

        gives just one option, not multiple.

        An alternative:
        $gisv=Gebeurtenis::getGebeurtenis()->where(‘spelvorm_id = :id’,[‘id’=>Yii::$app->spel->getSpelvormid()])->asArray()->all();

        gives also one option.

        What goes wrong?

        • m bala

          Hi,

          What i understood from your method, ‘gebeurtenisinspelvorm_id’ is the foreign key of the ‘tbl_gebeurtenis’ table (sound like user, user_type). You are showing the data in select box from ‘tbl_gebeurtenis’ table and your form is based on ‘tbl_gebeurtenisinspelvorm’ table After submitted the form What would you like to save in db like id, name etc.’

          • Arjen Meijer

            Well, I am struggling to get my head around Yii2.

            So, what I first did was to write a sql command:

            $gisv = Yii::$app->db->createCommand(‘SELECT gisv.gebeurtenisinspelvorm_id, g.samenvatting as samenvatting
            FROM `tbl_gebeurtenisinspelvorm` AS gisv
            LEFT JOIN tbl_gebeurtenis g ON gisv.gebeurtenis_id = g.gebeurtenis_id
            WHERE spelvorm_id =’.Yii::$app->spel->getSpelvormid());
            $geb = $gisv->queryAll();
            $keuzeData=ArrayHelper::map($geb,’gebeurtenisinspelvorm_id’, ‘samenvatting’);
            echo $form->field($model, ‘gebeurtenisinspelvorm_id’)->dropDownList($keuzeData,[‘prompt’=>’Kies een gebeurtenis’]);
            ?>

            This works correct. So the second part was to write the query in ‘Yii language’.
            That became:

            field($model, ‘gebeurtenisinspelvorm_id’)->dropDownList(ArrayHelper::map(Gebeurtenisinspelvorm::find()->where([‘spelvorm_id’=>Yii::$app->spel->getSpelvormid()])->all(), ‘gebeurtenisinspelvorm_id’, ‘gebeurtenis.samenvatting’),[‘prompt’=>’Kies een gebeurtenis’]); ?>

            That works too.

            So, my real question is, how do I think like Yii? Yii has several abstraction level added to sql. What are these abstraction levels and how do they interact? Which command works on which level? Can you make an article about that?

  • Nur Chalik Azhar

    How to add each id in data value “Lolos” and “Tidak” ? I don’t know, please advice me, you can my code this bellow.

    https://uploads.disquscdn.com/images/31dc47e914a724cb54cf4d921452284487cdd8604ca95e2083a0bff4c3b50903.jpg

  • alvaro lordelo

    How do I load IMG on dropDown list ??