AlexSultana
AlexSultana

Reputation: 39

Yii2 dropdown list selected value

I don’t understand how dropdown list works. I want to take selected value from dropdown list.

My code looks like:

<?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]) ?>
     <?= $form->field($model1, 'test')->dropDownList($items)->label(false);?>

    <button>Submit</button>
    <?php ActiveForm::end() ?>

where $items =[‘A’,‘B’,‘C’…‘Z’];

And the default displayed value for this is ‘A’, i want to change this value.

I’ve tried with $model1->test, but this is not my selected value.

Thanks!

Upvotes: 2

Views: 8515

Answers (3)

Prathap Goud Gantena
Prathap Goud Gantena

Reputation: 103

Use the following code you should change ModelName to your model class name, it will be work.

<?= $form->field($model, 'test')
      ->dropDownList(ArrayHelper::map(app\models\ModelName::find()->all(),'id','test'))
 ?>

Upvotes: 0

user206
user206

Reputation: 1105

In ActiveForm, your model field value is selected as the value.
In Html, there is another property that you can set the default value

You can use the activeDropDownList() in HTML for the given model attribute.

syntax in Yii2 ActiveForm :

<?= Html::field($yourModel, 'name_field_db')->dropDownList(
        [items-array of data],
        [options]
    ); ?>

syntax HTML:

<?= Html::dropDownList($name, $selection = null, $items = [], $options = []) ?>

data as array:

<?= $form->field($model, 'name')->dropDownList(['1' => 'on', '0' => 'off'],['prompt'=>'Select Option']); ?>

display the database data in the dropdownList via ArrayHelper::map.

    // get fields from database for make itemList
    $yourModels=model::find()->all(); // Query(by Active record or Query Builder or ..)

    $itemList=ArrayHelper::map($yourModels,'filed_id','filed-name');

    echo $form->field($newModel, 'filed-name')->dropDownList($itemList,['prompt'=>'Please select']);

Can for ActiveForm: $model->field = $model->isNewRecord? 'value' : $model->field;

Upvotes: 0

Serghei Leonenco
Serghei Leonenco

Reputation: 3507

If you need to make a prompt:

<?= $form->field($model, 'test')->dropDownList($items
    , 'prompt' => ' -- Select Value --']) ?>

If another scenario Lets say you chose to select 'B' from your array:

$items =[‘A’,‘B’,‘C’…‘Z’];

the key of 'B' is 1 so you need to do this:

<?= $form->field($model, 'test')->dropDownList($items)
,['options' => [1 => ['Selected'=>'selected']]
, 'prompt' => ' -- Select Value --']) ?>

Upvotes: 4

Related Questions