• 11

A PHP Error was encountered

Severity: Notice

Message: Undefined index: userid

Filename: views/question.php

Line Number: 191


File: /home/prodcxja/public_html/questions/application/views/question.php
Line: 191
Function: _error_handler

File: /home/prodcxja/public_html/questions/application/controllers/Questions.php
Line: 433
Function: view

File: /home/prodcxja/public_html/questions/index.php
Line: 315
Function: require_once

name Punditsdkoslkdosdkoskdo

CakePHP Session variable use in view page?

I have a variable contaning "username" and want to get these values via session to any of the view pages.

How can I get this session variable in the view ?

You can use $this->Session->read('myParam') in your Views files.
But you can't use $this->Session->write('myParam').

As noted here:

The major difference between the Session Helper and the Session Component is that the helper does not have the ability to write to the session.

  • 5
Reply Report

If you're in the controller, use the Session component. It's included, by default, in all the controllers. It has the Session::read() and Session::write() methods. Check out http://book.cakephp.org/view/173/Sessions for more information.

I believe, if the Session component is like some of the other components, you can use it inside the views. Try just doing $session->read() in your view code blocks. If that doesn't work, try doing a $this->Session->read(...). As a last resort, if none of those work, you can always use the good old PHP $_SESSION, although it's kinda veering outside the Cake framework. However, if you are sure you're not going to use Cake's Session management (and you don't really have to, IMO, as it's little more than a wrapper around $_SESSION), then just know when to properly apply the hack.

  • 0
Reply Report
      • 1
    • The Cake Session management is more than just a wrapper around $_SESSION, as it supports several more backends for storing session data. You can choose to write the session to a database to potentially share it across servers without having to change a single instance of $this->Session->write() in your app.
      • 2
    • True, although I think I would use a different method within php to change the other session handlers, rather than putting it inside Cake. Guess you caught me thinking mostly of how I think of the component, for how I would use it.
      • 1
    • @TravisLeleu Components are never made available in Views by Cake. I tested your beliefs and I'm pretty sure about that.

User this in you App controller's before filter

$this->Session->write('Person.eyeColor', 'username'); $green = $this->Session->read('Person.eyeColor'); $this->set('username',$green);

This will give you result as you want

  • -1
Reply Report

Warm tip !!!

This article is reproduced from Stack Exchange / Stack Overflow, please click

Trending Tags

Related Questions