How can I display selected value in dropdownlist in YII framework?

2.7k views Asked by At

I want to display the selected value in the drop-down list in Yii framework. I have generated code using the Yii CRUD operation. While adding and updating it uses the same view i.e. _form.php.

    <?php echo $form->labelEx($model,'prj_id'); ?>
    <?php
    $list = CHtml::listData(ProjectList::model()->findAll(array('order' => 'prj_name')), 'prj_id',       'prj_name');
    echo $form->dropDownList($PrjList, 'prj_id', $list);
    ?>
    <?php echo $form->error($model,'prj_id'); ?>

Suppose I have country names in my dropdown. While adding I have selected India and saved it in the database. At the time of updating it should display India as my selected country.
Thanks in advance.

3

There are 3 answers

1
Jap Mul On BEST ANSWER

You're using a different model for the dropdown..?

If you use $model as the model for the dropdownlist you'll save the ID of the selected value to the database. So then when you're going to update the record, the $model->prj_id will be set to the saved value, so that is the value it will display.

Don't know what $PrjList is, but I think it should be like the following code, since you're also displaying the label and error for this model and field.

  echo $form->dropDownList($model, 'prj_id', $list);

If for some reason you do need $PrjList as the model, make sure the prj_id is set to the saved value.

0
jithin On

use the following format

<?php  echo $form->dropDownList($PrjList,'prj_id', CHtml::listData(ProjectList::model()->findAll(array('order' => 'prj_name')),'prj_id','prj_name'),array('prompt'=>'Select Parent Menu','class'=>"span6 m-wrap"));?>
0
Justinas On

$form->dropDownList is same as CHtml::activeDropDownList. You have to pass model object and then that object has dropdown attribute set it will select it automatically.