How to load previously filled fields when model validation in Yii failed?

When a user clicks on creation and the model is not validated, my site redirects to the same page, displaying the same form. I am doing some research on how to load previously entered values ​​so as not to force the user to enter all this again. With firebug, I could observe the contents of the message, and they do not seem to contain such information.

Going up on the Internet, I saw that someone suggested using Ajax to submit a form and return JSON data, indicating whether the check was successful or not. However, I'm fairly new to Yii and PHP in general, so I need to be guided to get started with this.

Is there any other (simpler) way? Otherwise, how can I return JSON if the check was successful or not? Thank!

+3
source share
1 answer

It seems to me what you need to do is look at the $ _POST variables to see which dependent drop-down list was selected, and pre-visualize it when form validation fails, so the default Yii validation errors work. Using this link as an example:

First, reorganize part of the method actionDynamiccities()into a separate public (invalid) method in your controller:

public function getCitiesList($country_id) {
    $data=Location::model()->findAll('parent_id=:parent_id', 
              array(':parent_id'=>(int) $country_id));
    return CHtml::listData($data,'id','name');
}

Then consolidate your reorganized AJAX action as follows:

public function actionDynamiccities()
{
  $data = $this->getCitiesList($_POST['country_id']);
  foreach($data as $value=>$name)
  {
    echo CHtml::tag('option',
               array('value'=>$value),CHtml::encode($name),true);
  }
}

_form.php div #city_id, AJAXed , PHP-, :

<div id="city_id">
<?php if(isset($_POST['city_id'])): ?>
  <?php foreach($this->getCitiesList($_POST['country_id']) as $value=>$name): ?>
    <?php echo CHtml::tag('option', array('value'=>$value),CHtml::encode($name),true); ?>
  <?php endforeach; ?>
<?php endif; ?>
</div>

, $_POST ['country_id'], , .

, .

, . !

+2

All Articles