18

I want to show selected value in Yii2 dropdown,

$_GET Value:

  $id = $_GET["cid"];

Drop down code

  $form->field($model, 'userid')
    ->dropDownList(
          [User::getUser()],
          //[ArrayHelper::map(User::findAll(['active' => '1']), 'id', 'name')],
          ['prompt'=>'Select a user','id'=>'user_dropdown'],    
          ['options' =>
                    [                        
                      $id => ['selected' => true]
                    ]
          ]

        )->label('');           

but this method is not working!

Muhammad Shahzad
  • 9,340
  • 21
  • 86
  • 130

9 Answers9

23

Try this.

$model->userid=$id;
$form->field($model, 'userid')
->dropDownList(...)
->label('');
  • I was missing this line of code: $model->userid=$id; – Muhammad Shahzad Dec 22 '14 at 05:59
  • $model->country = 'United States'; = $form->field($model, 'country')->dropDownList($model['countries'])->label(false); ?> This did not work for me. What is mistake here? – Nilesh Kumar Feb 11 '16 at 08:36
  • 1
    @NileshKumar, *probably* your `$model->country` wants a country Id, not its name. So: `$model->country = $countryId` (1, 30, some else). – sdlins Apr 17 '16 at 19:30
8

Basically, you affect the options (your <option> elements) by using the value attribute's actual value as the array key in the dropDownList options array.

So in this case I have an array of states and the value attributes have the state abbreviation, for example value="FL". I'm getting my selected state from the Address table, which stores the abbreviation, so all I have to do is use that as my array key in the options array:

echo $form->field($model, 'state')->dropDownList($listData, ['prompt'=>'Select...', 'options'=>[$address->state=>["Selected"=>true]]]);

The documentation spells it out: http://www.yiiframework.com/doc-2.0/yii-helpers-basehtml.html#dropDownList()-detail

Steven McElveen
  • 429
  • 5
  • 6
6

i hope this will help you

$form->field($model, 'userid')
    ->dropDownList(
          [User::getUser()],
          //[ArrayHelper::map(User::find()->where('id' => $id)->all(), 'id', 'name')],
          ['prompt'=>'Select a user','id'=>'user_dropdown'],    
          ['options' =>
                    [                        
                      $id => ['selected' => true]
                    ]
          ]

        )->label('');
Kalai S
  • 986
  • 3
  • 14
  • 25
3
$model->userid = $_GET['cid'];
$form->field($model, 'userid')
->dropDownList( 
      $items,                   //Flat array('id'=>'val')
['prompt'=>'']                  //options
)->label('');
2
<?php 
$selectValue = $_GET['tid']
echo $form->field($model, 'tag_id')
            ->dropdownList(
                ArrayHelper::map(Tag::find()->where(['visibility'=>'1'])->orderBy('value ASC')->all(), 'tag_id', 'value'),
                ['options' => [$selectValue => ['Selected'=>'selected']]], 
                ['prompt' => '-- Select Tag --'])
            ->label(false);
?>

This code will Auto Select the selected value received as input. Where $selectValue will be numeric value received from GET method.

Final output : <option value="14" selected="selected">NONE</option>

Vikram
  • 35
  • 1
  • 10
1

Ok, if you are using ActiveForm then value of your model field will be used as the selected value. With Html helper dropDownList function accepts another parameter selection doc. Example:

$id = $_GET["cid"];
\yii\helpers\Html::dropDownList('userid', $id, [ArrayHelper::map(User::findAll(['active' => '1']), 'id', 'name'), [......])
Fortran
  • 593
  • 4
  • 14
1

This is my S.O.L.I.D approach.

Controller

$model = new User();
$model->userid = $id; #this line does the magick. Make sure the $id has a value, so do the if else here.
return $this->return('view', compact('model'))

But, if you prefer the setter method. Do this...

# Model
class User extends ActiveRecord
{
    public function setUserId(int $userId): void
    {
        $this->userid = $userId;            
    }
}

# Controller
$model = new User();
$model->setUserId($userId);

View (view is as-is)

$form->field($model, 'userid')
->dropDownList(...)
->label('');
Jake Pucan
  • 628
  • 8
  • 11
0

Use this code below:

$category = \backend\models\ProductCategory::find()->WHERE(['deleted'=>'N'])->all();

$listData = ArrayHelper::map($category,'product_category_id','category_name');

echo $form->field($model, 'product_category_id')->dropDownList($listData,['prompt'=>'Select']);
Hunny
  • 31
  • 5
0

All of the options I've added are unrequired. What is written in the 'value' index is what dropdown item will be selected as default. Prompt just displays a first option that doesn't have a value associated with it.

echo $form->field($model, 'model_attribute_name')
    ->dropDownList($associativeArrayValueToText, 
    [
        'value'=> $valueIWantSelected, 
        'prompt' => 'What I want as a placeholder for first option', 
        'class' => 'classname'
    ]);

You'll find the function that assigns this in the following file:

vendor/yiisoft/yii2/helpers/BaseHtml.php

public static function renderSelectOptions($selection, $items, &$tagOptions = [])

Also from the function you can see that you can add an optgroup to your dropdown, you just need to supply a multidimensional array in where I've put $associativeArrayValueToText. This just means that you can split your options by introducing group headings to the dropdown.

Community
  • 1
  • 1
Fi Horan
  • 503
  • 4
  • 14