1

I want to call an action of controller file from a .ctp file in cakephp. is it possible? yes, than how? please help. for e.g. I have an action in controller. users_controller.php

<?php
class UsersController extends AppController {

    function get_category() {
        ....
    }

}
?>

I want to call it from /question/index.ctp file.

dovid
  • 6,354
  • 3
  • 33
  • 73
gautamlakum
  • 11,815
  • 23
  • 67
  • 90
  • 4
    Why do you want to do this? It is in violation of good MVC practices, and to me it screams out "something wasn't setup properly". – Travis Leleu Nov 01 '10 at 19:49

3 Answers3

2

The proper way to do this is:

$this->requestAction(array('controller' => 'users', 'action' => 'get_category'));

Creating the url the CakePHP way will increase performance (it won't have to use Router). Also will always work, while doing it like: "users/get_category" might cause some trouble when you're not in the index page.

It should only be used in elements (with cache especially), if the case is different - reefer to what Travis Leleu wrote in his comment.

pawelmysior
  • 3,190
  • 3
  • 28
  • 37
2

It should be noted that you should NOT rely on requestAction as a common practice. requestAction is an extremely taxing call and should only be used if you cannot organize your code in any other way.

Ideally, you'd send the data you need from your controller action to the view rather than calling back up to your controller.

function my_action() {
   ...
   $this->set('category', $this->getCategory());
}
jmking
  • 259
  • 1
  • 6
1

you can call it like $this->requestAction('controller'=>'users','action'=>'get_category')

mentes
  • 120
  • 3
  • 14
  • as far as I know $this->requestAction('controller'=>'users','action'=>'get_category') this one should be $this->requestAction(array('controller'=>'users','action'=>'get_category')) I didnt try it other way – mentes Nov 01 '10 at 19:54