views:

47

answers:

2

Hi,

I have an edit action in the users controller. What I want to do is redirect anyone to a different action if their Auth.User.id does not equal the id of the user they are trying to edit.

I can access variables in my views like this:

if($session->read('Auth.User.id') != $id){

but this doesn't work in my controller. Getting:

Undefined variable: session

How do I access session data within a controller? also, if any has a better way of achieving what I want to do, feel free to add!

Thanks,

Jonesy

+6  A: 

You must first add Session as a component in your controller:

var $components= array('Session');

You can then access it in your methods via $this->Session

webbiedave
+1 for general correctness, but he should add Session as a component, not a helper. (though usually both.)
Stephen
Thanks, Stephen. I mixed up components and helpers. I've edited.
webbiedave
+3  A: 

You can read Session data in a controller with $this->Session->read('Auth.User.id'); The CakePHP Session component, if I remember correctly, is automatically loaded into all controllers unless you have defined the default components elsewhere. If $this->Session is undefined, include it into your $components array in your controller like var $components = array('Session');

It's important to note that Helpers are not the same as Components. Generally speaking, Components are extended functionality for your Controller. Whereas Helpers are extended functionality for your view.

For a complete look at all possible methods, the CakePHP Cookbook will be invaluable for you! http://book.cakephp.org/view/1310/Sessions

kmark937