How to pass controller variable to view in CakePHP?

This is my controller:

class MyWorksController extends AppController{
    function index(){
        $workLevel = $this->getWorkLevel();
        if($workLevel == 3){
            $recreationID = $this->getRecessId($workLevel );
            $this->set('recreationID', $recreationID);
            $this->redirect('/MyWorks/report1/');
        }
        else{ 
            $this->redirect('/MyWorks/report2/');
        }     
    }
    function report1(){}

    function report2(){}
}

I want to send $recreationID value to my view page's form, in the following way:

echo $form->create('FishingTimeAllocations', array('tmt:validate'=>'true', 'action'=>'index', 'recreationID '=>$recreationID ));?>

However, I was unsuccessful in doing so, and the error I keep getting is this:

Undefined variable: recreationID 

What is the problem in my code and what is the correct way to get my desired thing done?

CakePHP version 1.2, PHP version 5.2, MySQL version 5.1.36. (I'm aware I'm running old versions of these items of software - nothing I can do about that at the moment).

Upvotes: 0

Views: 1771

Answers (2)

Death-is-the-real-truth
Death-is-the-real-truth

Reputation: 72269

You can not send variables using set() to other actions. If you want to use the variable to another page (view file), you need to do it with these two possible ways:

  1. set in session and then use it.
  2. pass as url parameter.

Note:- In these two way session way is more secure.

Upvotes: 8

Kamoris
Kamoris

Reputation: 505

This actually doesn't work cause $recreationID variable is set for your index() view. If you want have this variable in report1() you should do it this way:

function index() {
    ...
    $this->redirect('/MyWorks/report1/' . $recreationID);
    ...
}

function report1($recreationID){
    $this->set('recreationID', $recreationID);
}

It is also possible to accomplish with Session.

Upvotes: 2

Related Questions