tags:

views:

780

answers:

3

i need some help

which is when i on my index.ctp/view.ctp, i need to call to my controller function to perform some task. what code i can use to perform this action?

  • i need to call to my controller function, which send in a value (user_id) to the function and get me a certain action. how can i do that? i might calling in a javascript function as well.
+6  A: 

If you need to call a Controller function from the View, you're doing it wrong. It's not proper MVC.

Having said that, requestAction would be the proper, albeit slowest way to do so. You could hack around a bit more and get an instance of the Controller from the ClassRegistry. But I'd seriously recommend you to restructure your program flow so you don't need to do this to begin with.

deceze
A: 

If your task doesn't generate any output - you might want to consider doing it in the controller before you even get to the view stage.

If your task has some form of output - use requestAction with a view Element

  1. http://bakery.cakephp.org/articles/view/creating-reusable-elements-with-requestaction

That link should be a good starting point. There are also good posts by Mark Story on his blog that detail the actual performance of requestAction and it really isn't that bad if you don't abuse it all over the place.

  1. http://mark-story.com/posts/view/how-using-requestaction-increased-performance-on-my-site
  2. http://mark-story.com/nodes/view/reducing-requestaction-use-in-your-cakephp-sites-with-fat-models

If you really need to trigger some sort of logic in a predictable way and that logic might happen in more than one place you can also use an event observer pattern to trigger the controller action you need to run.

  1. http://cakealot.com/2009/04/eventful-a-cakephp-event-system/
Abba Bryant
A: 

You should probably perform the task in the controller before you get the view. But if you need to do some view work on the data you are displaying you might want to consider making a Helper class.

  1. http://book.cakephp.org/view/101/Creating-Helpers
Jack B Nimble