Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

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());
}

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top