Thursday, 11 August 2016

Yii2.0 DropDownList

Default DropDownList

Yii2.0 default dropdownlist syntaxt.
1<?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.
1<php echo $form->field($model'name[]')->dropDownList($listData,
2                        ['prompt'=>'Select...']);>
Using below code, we can display the database value (via model) in dropdownlist of yii2.0 framework.
01<?php
02//use app\models\Country;
03$countries=Country::find()->all();
04
05//use yii\helpers\ArrayHelper;
06$listData=ArrayHelper::map($countries,'code','name');
07
08echo $form->field($model'name')->dropDownList(
09                                $listData,
10                                ['prompt'=>'Select...']);
11?>

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

01<??php
02...................
03public function actionCreate()
04{
05    $model new Population();
06    // Default Selection for country code
07    $model->country='IN';
08    if ($model->load(Yii::$app->request->post()) && $model->save()) {
09            return $this->redirect(['view''id' => $model->code]);
10    else {
11        return $this->render('create', [
12            'model' => $model,
13        ]);
14    }
15}
16public function actionUpdate($id)
17{
18    $model $this->findModel($id);
19    return $this->render('update', [
20        'model' => $model,
21    ]);
22}
23...................
24?>

Create/Update Form Code

01<??php
02use yii\helpers\Html;
03use yii\widgets\ActiveForm;
04use yii\helpers\ArrayHelper;
05?>
06
07<?div class="population-form">
08    <??php $form = ActiveForm::begin(); ?>
09    ...................
10    <??php
11        //$model->name='IN';
12        $listData=ArrayHelper::map($countries,'code','name');
13        echo $form->field($model'name')->dropDownList($listData, ['prompt'=>'Choose...']);
14    ?>
15    ...................
16    <??php ActiveForm::end(); ?>
17<?/div>


Yii2.0 DropDownList

No comments:

Post a Comment