CakePHP passing values between controllers

2019-07-27 10:16发布

问题:

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');