1

我有在模式中绑定的下拉菜单。使用以下代码:

public function getYears()
{
    for ($i=date('Y');$i>=2012;$i--)
    {
            $years["{$i}"]="{$i}";
    }
   return $years;                  
}

我的观点是:

 <div class="row">
 <?php echo $form->labelEx($model,'year'); ?>
 <?php echo CHtml::activedropDownList($model,'years',$model->getYears(),array('class'=>'myClass')); ?>
 <?php echo $form->error($model,'year'); ?>

 <?php echo $form->labelEx($model,'name'); ?>
 <?php
$this->widget('zii.widgets.jui.CJuiAutoComplete', array(
'name'=>'name',
'source'=>$this->createUrl('reports/autocompleteTest'),
'options'=>array(
        'delay'=>300,
        'minLength'=>2,      
        'showAnim'=>'fold',
),
));
?>
  <?php echo $form->error($model,'name'); ?> 

  <?php echo $form->labelEx($model,'Status'); ?>
  <?php echo $form->dropDownList($model,'is_active',array("1"=>"Active","0"=>"InActive")); ?> 
  <?php echo $form->error($model,'Status'); ?>

   </div>
<div class="summary_btn buttons"> <?php echo CHtml::submitButton('Search'); ?> </div>
<?php $this->endWidget(); ?>

现在,当我单击一个按钮时Search,我的页面正在回发。它重新绑定下拉列表。

我不知道如何在单击按钮后将所选值保留在下拉列表中。

4

2 回答 2

2

在行动中:

$model->setAttributes($_POST[get_class($model)]);

在模型中:

function rules(){
    return array(
        //other rules
        array('years', 'safe'), //or any other validation
    )
}
于 2013-08-14T12:28:53.893 回答
1

setAttributes的模型应该来自$_POST,所以 Yii 会将模型值重新分配给组件,就像保存模型一样,但不保存:

public function someAction()
{
    // load model somewhere
    $model = $this->_loadModel();
    if($_POST['modelName'])
    {
        $model->setAttributes($_POST['modelName']);
    }
    $this->render('someView', ['model' => $model]);
}

编辑:

发表评论后,我注意到您的模型带有getYears方法,Yii 将其用作属性的 getter years,如getters and setters tutorial 中所述。例如,您应该重命名它getYearRanges。并确保您years的模型中有属性来保存当前years值,并具有HarryFink answer 中的规则。

于 2013-08-14T12:11:08.470 回答