如何在更新函数中获取Yii dropDownList的选定值?

问题描述:

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 ?

我在更新模型值时遇到问题,其中一个模型属性是从dropDownList中选择的数字 ,这是我的代码: p>

 &lt;?php $ images = Homepage :: model() - &gt; findAll(); 
 if(!empty($ images)  ){
 $ data = array(); 
 $ x = 1; 
 foreach($ images as $ i){
 
 array_push($ data,$ x); 
 $ x ++; 
}  
?&gt; 
&lt;?php echo $ form-&gt; labelEx($ model,'order');  ?&gt; 
&lt;?php echo $ form-&gt; dropDownList($ model,'order',$ data,array(
'empty'=&gt;'选择图片顺序',
'id'=&gt;  ;'订购'));  ?&gt; 
  code>  pre> 
 
 

此dropDownList包含db中模型(表)的记录数,问题出在更新函数中,例如:on the 创建(图片1)我选择1作为订单值,然后当我去更新时,我得到的预选项是2(这是listData的最后一个值)而不是1,那么错误是什么 在这里? p> div>

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.