2

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!

3 Answers 3

4

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 --']) ?>
Sign up to request clarification or add additional context in comments.

Comments

0

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;

Comments

0

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'))
 ?>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.