简体   繁体   中英

How to get the selected value of Yii dropDownList in the update function?

I have a problem in updating my model values, one of the model attributes is a number that is selected from a dropDownList, here is my code:

<?php $images = Homepage::model()->findAll();
                        if(!empty($images)){
                            $data = array();
                            $x = 1;
                            foreach ($images as $i){

                                array_push($data, $x);
                                $x++;
                            }
                ?>
                <?php echo $form->labelEx($model,'order'); ?>
                <?php echo $form->dropDownList($model, 'order', $data, array(
                    'empty'=>'Select image order',
                    'id'=>'order')); ?>

this dropDownList is containing the number of records of model (table) in the db, the problem is in the update function, for example: on the creation of (image 1) I selected 1 as the order value, then when I go to the update, I got the pre-selected option is 2 (which is the last value of the listData) instead of 1, so what is the error here ?

Im not a Yii expert but i think you are doing it wrong, Im using this code below and it works fine im getting the id from the database and showing it in the dropDown list, try it maybe it helps or check http://www.yiiframework.com/wiki/48/by-example-chtml/#hh5 ,

    <?php echo $form->labelEx($model,'order_id'); ?>
    <?php echo $form->dropDownList($model,'order_id',
     CHtml::listData(Homepage::model()->findAll(),'order_id','order_id'),
     array('empty'=>'--Select order --') ); ?>

You need to define the selected in the options

'options'=>array($model->id => array('selected'=>true))

Roughly your code will look like this now

echo $form->dropDownList($model, 'order', $data, array(
    'empty'=>'Select image order',
    'id'=>'order',
    'options'=>array($model->id =>array('selected'=>true))             
));

Give it a try this will help.

I think it might be with the $data variable.

In my experience with Yii, i always use associative array ($key=>$value) for dropdown

so maybe something like

$data = array('1'=>'Test', '2'=>'Test 2');

In this way, Test and Test 2 will be the values displayed on the dropdown itself and '1' and '2' will be the values stored in the $model and the database.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM