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!

2
  • Arah.. I just forget to write echo, inside the PHP tags. <?= echo $form->field(....) ?> Commented Dec 22, 2014 at 5:57
  • Also I was missing this line of code: $model->userid=$id; Commented Dec 22, 2014 at 6:00

9 Answers 9

23

Try this.

$model->userid=$id;
$form->field($model, 'userid')
->dropDownList(...)
->label('');
Sign up to request clarification or add additional context in comments.

3 Comments

I was missing this line of code: $model->userid=$id;
$model->country = 'United States'; <?= $form->field($model, 'country')->dropDownList($model['countries'])->label(false); ?> This did not work for me. What is mistake here?
@NileshKumar, probably your $model->country wants a country Id, not its name. So: $model->country = $countryId (1, 30, some else).
10

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

Comments

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('');

1 Comment

Useful for multiple select as well.
3
$model->userid = $_GET['cid'];
$form->field($model, 'userid')
->dropDownList( 
      $items,                   //Flat array('id'=>'val')
['prompt'=>'']                  //options
)->label('');

Comments

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>

Comments

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'), [......])

1 Comment

I got this error: Call to a member function formName() on a non-object
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('');

Comments

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']);

Comments

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.

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.