I’m completely new in Yii and suffering to update a form field based on another field’s on change event on the same form. It’s a simple city look up based on ZIP code. I checked many forum threads, but didn’t find solution.
I have a table where I store all cities with ZIPs.
Here’s the code for the ZIP filed in my _form.php:
So based on the value of this filed I would like to update the field called "Beszallito_kapcsolattarto" on the same form.
And here is my action in my controller:
public function actionGetTelepulesByIrsz(){
$data=Telepules::model()->find('irsz=:irsz',
array(':irsz'=>$_POST['irsz']));
echo CHtml::encode($data->nev);
}
What I recognized is that when I use a fix value in my action instead of getting the value of the $_POST variable it’s working fine, so I guess there should be some problem during when I’m trying to pass the value of my variable to the controller.
If you know a tutorial or example about this and you can paste it here I would appriciate it.
Ok. Now the problem comes, that I can store the values in my database though, but since create and update actions are using the very same form (namely _form.php in the appropriate view) the stored data is not loading when I’m about to update the record, since I’m using CHtml::textFiled instead of $form->textField.
Anybody has any general guideline how can I handle this?
I think I have the answer for this question and it’s quite easy with Yii framework (Yes It Is! ). I just need to take care of values of additional fields in the appropriate action.
In my case I have to extend my actionUpdate() action to fill in my extra textFields as requested. I’m about to finish this logic now. I’ll post it here once I finish.
Instead of setting the field values in actionUpdate action I could manage to retrieve the values on view level by checking if Yii calls the update or create action like this:
I have a model called Telepules and I created the following function in it which returns with the ZIP of the city based on city_id which is stored on my _form as a hidden field:
public function getTelepulesIrszById($telepules_id)
{
$telepules = $this->find('id=:id',
array(':id'=>$telepules_id));
return $telepules->irsz;
}
With this solution both update and create actions are working fine with city look-up functionality. When the update action is called the code fills in the ZIP and city name fields automatically based on city_id (my hidden field). And when create action is called the form remains empty.
If anybody has any other/simpler solution for this I would be happy to see. I know that the basic Yii philosophy is to separate the application logic from view but as I mentioned I’m quite new in Yii.