如何从视图页面表单中获取隐藏字段值并将其设置为cookie值并在cakephp中的相同视图页面中进行检索

时间:2017-01-26 16:27:16

标签: cakephp

在此先感谢,我有一个index.ctp页面,其中我有一个表格,其中有一个隐藏字段,其值为" 2"。提交表单时,将值传递给控制器​​并将cookie设置为

$cookieVal =$this->request->data['hideCookieVal'];              
$this->cookie->write('hideNextCookieVal',$cookieVal, false, 3600);

我试图传入一个变量来获取index.ctp中的值,所以我使用了这个

$this->set('nextCookie',$this->Cookie->read('hideNextCookieVal'));

在index.ctp页面中,我以变量名称$nextCookie访问此值。 我在if条件中使用了这个变量来显示HTML页面的其他部分,如果设置了cookie但是,它会抛出错误

  

错误:在非对象上调用成员函数write()   文件:D:\ wamp \ www \ invl_exams \ app \ Controller \ UsersController.php
  行:135

我的代码如下:

UsersController.php

<?php
App::uses('CakeEmail', 'Network/Email');

class UsersController extends AppController
{
  function index()
   { 

Line 134  $cookieVal = $this->request->data['hideCookieVal'];              
Line 135  $this->cookie->write('hideNextCookieVal',$cookieVal, false, 3600);
Line 136  $this->set('nextCookie',$this->Cookie->read('hideNextCookieVal')); 

   }
 }

index.ctp page 

<form class="shopping-cart" name="cartTable" id="cartTable" method="post" action="<?php echo $this->webroot ?>users/index">

 <input type="hidden" name="hideCookieVal" value="2">

<button type="submit" class="next pull-right" id="nextId">NEXT</button>
</form>
<?php
if($nextCookie == 2) 
{

?>

<section>
  <table>
    <!-- Table content here -->
  <table>
</section>

<?php
}
?>

1 个答案:

答案 0 :(得分:0)

您需要在控制器中加载CookieComponent,并且Cookie加上大写的c字母

<?php

    App::uses('CakeEmail', 'Network/Email');

    class UsersController extends AppController {
        //Add this line
        public $components = array('Cookie');

        function index() {
            Line 134  $cookieVal = $this->request->data['hideCookieVal'];
            //Change cookie to Cookie              
            Line 135  $this->Cookie->write('hideNextCookieVal',$cookieVal, false, 3600);
            Line 136  $this->set('nextCookie',$this->Cookie->read('hideNextCookieVal')); 
        }

    }
相关问题