Yii Framework 2 : 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>
	

Leave a Reply

Your email address will not be published. Required fields are marked *