如何将控制器变量传递给 CakePHP 中的视图?

How to pass controller variable to view in CakePHP?

这是我的控制器:

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

我想通过以下方式将 $recreationID 值发送到我的视图页面的表单:

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

但是,我这样做没有成功,我不断收到的错误是:

Undefined variable: recreationID 

我的代码有什么问题,完成我想要的事情的正确方法是什么?

CakePHP 1.2 版,PHP 5.2 版,MySQL 5.1.36 版。 (我知道我是这些软件的 运行 旧版本 - 目前我对此无能为力)。

您不能使用 set() 将变量发送到其他操作。如果你想将变量用于另一个页面(查看文件),你需要通过以下两种可能的方式来实现:

  1. 在会话中设置,然后使用。
  2. 作为 url 参数传递。

注:-这两种session方式更安全。

这实际上不起作用,因为为您的 index() 视图设置了 $recreationID 变量。 如果你想在 report1() 中有这个变量,你应该这样做:

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

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

也可以用Session来完成