Yii2 dropdown selected value

down vote favorite

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!

Hi dude…refer this link

http://www.yiiframework.com/wiki/674/managing-your-nested-dropdown-dependency-with-depdrop-widget

Please I got a similar problem on Yii2:

I want to insert value into a textInput field based on selection from a dropdownlist. Here is my code:

<?= $form->field($model, ‘course_taken’)->dropDownList(ArrayHelper::map(Courses::find()->all(),‘course_code’,‘course_code’)) ?>

<?= $form->field($model, ‘course_details’)->textInput([‘maxlength’ => true]) ?>

So when the user selects a course from the dropdownlist, the testInput will display the course details of the selected row. Both course_taken and course_details are columns from the same database table.

Thanks in advance.

Dont use id , because Active form template generates a id for each field of that model you used.

Hi Muhammad Shahzad,

Set your GET value for model variable, then place the drop-down-list… It may work & solve your problem


$model->userid = isset($_GET["cid"]) ? $_GET["cid"] : '';

$form->field($model, 'userid')->dropDownList([User::getUser()],['prompt'=>'--Select--']); 

Thanks dude!

I am not sure how you want it exactly, but if you want to make form fields that are dependent on each other, then you have to use JS probably.




$js = "

$(\"#contollername-modelattribute\").change(function () {

         //DO STUFF HERE WHEN THE DROPDOWN IS CHANGED


         var text = $(\"#contollername-modelattribute option:selected\").text();

         var val = this.value;

         console.log(text);

         $(\"#contollername-modelattribute2\").val(text);

});


";


$this->registerJs($js, \yii\web\View::POS_READY, 'my-options');



This piece of code would change your textfield value to be the equal as the selected value in the dropdown.

Be aweare of the javascript DOM addressing.

#contollername-modelattribute

For you it would be #controllername-course_taken or #controllername-course_details etc. where #controllername is the name of the controller processing the current form, without any special characters. Eg.: Your controller is my-courses, then you address it #mycourses-course_taken.

You could use two dropdowns or an array with the descriptions to change the textfield value or you can write a function to AJAX the description with JS whenever the dropdown is changed.