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

时间:2015-03-23 11:15:56

标签: php mysql 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。 (我知道我正在运行这些软件的旧版本 - 目前我无能为力。)

2 个答案:

答案 0 :(得分:9)

您无法使用set()向其他操作发送变量。如果要将变量用于其他页面(视​​图文件),则需要使用以下两种方式进行:

  1. 设置会话然后使用它。
  2. 传递为url参数。
  3. 注意: - 在这两种方式中,会话方式更安全。

答案 1 :(得分:2)

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

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

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

也可以通过Session完成。