Reputation: 27845
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 ?
Upvotes: 9
Views: 26297
Reputation: 33986
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.
Upvotes: 5
Reputation: 521995
There's a SessionComponent available in your Controller that you can use like $this->Session->write('Name', 'Value');
. Analogously there's also the SessionHelper for the View, which does very similar things and can be used like $session->read('Name');
.
Upvotes: 12
Reputation: 2140
To use it in a helper you must remember to include it in your $helpers declaration:
class Foo extends AppHelper
{
var $helpers = array('Session','Bar');
Upvotes: 2
Reputation: 473
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
Upvotes: -1
Reputation: 921
You can pass the Session object from controller to a view template using
$this->set('session',$this->Session);
Then in view file
use $session->read('SessionName');
Upvotes: -2
Reputation: 4230
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.
Upvotes: 0