我有一个绑定在模态中的下拉列表。使用以下代码:
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
时,我的页面正在返回。它会重新绑定下拉列表。
我不知道点击按钮后如何在下拉列表中保留所选的值。
在操作中:
$model->setAttributes($_POST[get_class($model)]);
在模型中:
function rules(){
return array(
//other rules
array('years', 'safe'), //or any other validation
)
}
您应该从$_POST
中setAttributes
您的模型,因此Yii将重新分配模型值以形成组件,就像保存模型一样,但不保存:
public function someAction()
{
// load model somewhere
$model = $this->_loadModel();
if($_POST['modelName'])
{
$model->setAttributes($_POST['modelName']);
}
$this->render('someView', ['model' => $model]);
}
编辑:
在评论之后,我注意到您有了带有getYears
方法的模型,Yii将其用作属性years
的getter,如getters和setters教程中所述。您应该重命名它,例如getYearRanges
。并确保您的模型中有years
属性来保持当前的years
值,并有HarryFink中的规则作为答案。