CakePHP passing values between controllers

霸气de小男生 提交于 2019-12-13 18:03:25

问题


I want to pass values from one controller to another. For example I have a Conference controller and I want to create a new Event. I want to pass the Conference id to the event to make sure those two objects are associated. I would like to store in the ivar $conference using beforeFilter method.

Here is my beforeFilter function in the Events controller

public function beforeFilter() {
    parent::beforeFilter();

    echo '1 ' + $this->request->id;
    echo '2 ' +     $this->request['id'];
    echo $this->request->params['id'];
            if(isset(   $this->request->params['id'])){
             $conference_id =   $this->request->params['id'];       
        }
        else{
         echo "Id Doesn't Exist";   
        }   
}

Whenever I change url to something like:

http://localhost:8888/cake/events/id/3

or

http://localhost:8888/cake/events/id:3

I am getting an error saying that id is not defined.

How should I proceed?


回答1:


when you're passing data via url you can access it via

$this->passedArgs['variable_name'];

For example if your URL is:

http://localhost/events/id:7

Then you access that id with this line

$id = $this->passedArgs['id'];

When you access a controller function that accepts parameters through url, you can use those parameters just as any other variable, like for example say your url looks like this

http://localhost/events/getid/7

Then your controller function should look like:

public function getid($id = null){
  // $id would take the value of 7
  // then you can use the $id as you please just like any other variable 
}



回答2:


In the Conferences Controller

$this->Session->write('conference_id', $this->request->id); // or the variable that stores the conference ID

In the Events controller

$conferenceId = $this->Session->read('conference_id');

Of course, on top you need

public $components = array('Session'); 


来源:https://stackoverflow.com/questions/21938578/cakephp-passing-values-between-controllers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!