When the user clicks on create and the validation of the model fails, my site redirects to the same page displaying the exact same form. I have been doing some research on how to load the previously typed in values so as not to make the user type it all in again. With firebug i could observe the post contents and these dont seem to contain such information.
Looking up on the internet i saw someone suggesting to use Ajax to submit the form and have it return JSON data specifying whether validation was successful or not. However, im pretty new to Yii and PHP altogether, so i would need some guidance to be able to get started with this.
Is there another (simpler) way? In case not, how could i have a JSON return specifying if the validation was successful or not? Thank you!
It seems to me like what you need to do is look at the $_POST variables to see which dependent dropdown was selected, and pre-render it when the form validation fails so Yii’s default validation errors work. Using this link as an example:
First, refactor out part of the
actionDynamiccities()method into a separate public (non-action) method in your controller:Then fix your refactored AJAX action like so:
Then in your _form.php view file, in the #city_id div where the second dropdown would be AJAXed in by the first, add a little PHP snippet like this:
This way, if you have already submitted the form and the $_POST[‘country_id’] is set, the dependent dropdown is already rendered and it should display the appropriate validation errors.
If the user selects a different country the city dropdown should be replaced like normal still.
I didn’t test this code but it should work in principle. Good luck!