CakePHP: best way to call an action of another controller with array as parameter? CakePHP: best way to call an action of another controller with array as parameter? arrays arrays

CakePHP: best way to call an action of another controller with array as parameter?


I would not advice to use the method requestAction but rather import, and instantiate the needed controller.

CakePHP doc says about requestAction that:

"It is rarely appropriate to use in a controller or model"

http://book.cakephp.org/view/434/requestAction

Once you imported and loaded the controller you can call any method of this controller with its parameters.

<?php  //Import controller  App::import('Controller', 'Posts');  class CommentsController extends AppController {    //Instantiation    $Posts = new PostsController;    //Load model, components...    $Posts->constructClasses();    function index($passArray = array(1,2,3)) {      //Call a method from PostsController with parameter      $Posts->doSomething($passArray);    }  }?>


Would it be appropriate for you to move the logic from the second controller into its model, then do something like this in your first controller's action?

$var = ClassRegistry::init('SecondModel')->myMethod($array);$this->set(compact('var'));

Then, in the view for the first controller's action, you can use that data.

I always try to keep controller methods to actions you can hit through the browser, put as much logic in my models, call foreign model methods from controllers actions that need data from models that aren't the model for that controller, then use that data in my views, and if it's data that is viewed frequently, I create an element for it.


As of CakePHP 1.2.5, you should be able to pass various parameter types through the second parameter in requestAction(). e.g.:

$this->requestAction('/users/view', array('pass' => array('123')));

Then in the UsersController:

function view($id) {    echo $id; // should echo 123 I believe, otherwise try $this->params['pass'].}

Instead of using 'pass' above, you can alternatively try 'form' and 'named' to pass form/named parameters respectively.