Pergunta

I have dropdown that is binding in modal. using the below code:

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

and my view is :

 <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(); ?>

Now when i click on a button Search, my page is making post back. And it rebinds the dropdown list.

I dont know how can i retain the selected value in dropdown after the button click.

Foi útil?

Solução 2

You should setAttributes of your model from $_POST, so Yii will reassign model values to form components, just like with saving models, but without save:

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

EDIT:

After comments I noticed that you have your model with getYears method, which Yii uses as getter for attribute years, as explained in getters and setters tutorial. You should rename it for example getYearRanges. And ensure you have years attribute in your model to hold current years value, and have rule as in HarryFink answer.

Outras dicas

In the action:

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

In the model:

function rules(){
    return array(
        //other rules
        array('years', 'safe'), //or any other validation
    )
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top