views:

29

answers:

2

I'm stll relatively new to cakephp (1.3) and struggling with where to put the code to do the following.

I want to display fields from a database (as usual) but, if the value for one of the fields is null, I want to look up the value using a web service and, if the request is successful, write the returned value to the database before returning the new value. I've already written the code to look up the web service, I'm just not sure exactly where to put it (model or controller) to make it work most effectively.

Thanks - I'd appreciate any suggestions.

A: 

Would you put your web service call in the controller, and pass the returned data to the model to be put into the database. Tom.

Tom Austin
Since it's not really routing a request (the trigger is whether the initial data retrival includes a specific field equal to null), the controller might not be the best place to put this. I think placer's solution is a good one -- keep all the data manipulation in the model.
Travis Leleu
+2  A: 

I would suggest putting this in your Model within a afterFind() function. This function is automatically triggered after any find() operations are performed within that model. Within this function, you could check the value of the field, perform your lookup if necessary and update the field.

Read about how to implement this here: http://book.cakephp.org/view/1048/Callback-Methods

Michael
Thanks, I've done this and it works well - I can modify the results of the find() operation. I would now like to save the modified data to the database - how do I go about doing this?
Tomba
Within the afterFind() function, you can change the $results as needed and then call $this->Model->save($results) which should update your record with the modified field. Make sure you return the modified $results so it's available in the controller after this function ends.
Michael
$this->Model->save($results) doesn't work (I've replaced Model with my model name) but thanks for your help
Tomba
Sorry, save() might not like the format of the $results. You might try **$this->Model->saveField()** instead. (http://api13.cakephp.org/class/model#method-ModelsaveField) Either way, I highly recommend reading through the Cookbook (the page I linked you to) to get the most out of Cake and might answer questions which will inevitably come up later.
Michael
I finally got it to work with $this->save($results[$index]); inside an array of foreach ($results as $index => $result).
Tomba
Awesome! I'd imagine there to be a better way. If you look at the expected format of data sent to the save() function (http://book.cakephp.org/view/1031/Saving-Your-Data) You could probably format it to look the same way and save it in one go. :)
Michael