简体   繁体   English

如何通过控制器变量在CakePHP中查看?

[英]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: 我想通过以下方式将$ recreationID值发送到视图页面的表单:

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. CakePHP版本1.2,PHP版本5.2,MySQL版本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). (我知道我正在运行这些软件的旧版本-目前我对此无能为力)。

You can not send variables using set() to other actions. 您不能使用set()将变量发送到其他操作。 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. 作为url参数传递。

Note:- In these two way session way is more secure. 注意:-这两种方式的会话方式更加安全。

This actually doesn't work cause $recreationID variable is set for your index() view. 这实际上不起作用,因为为您的index()视图设置了$recreationID变量。 If you want have this variable in report1() you should do it this way: 如果要在report1()包含此变量,则应采用以下方式:

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

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

It is also possible to accomplish with Session. 使用Session也可以完成。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM