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
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
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
Related
I need to reach my cookies from the view files. I'm aware that one can use CookieComponent inside a controller and pass cookie values to view files with set().
Visitors of our website has an options page. User's selections are saved to cookies. Up to now I was using CookieComponent and checking the values and making my works with that values. But now I added new options choices, so I need to reach them from my view files, or from my helpers. If I pass cookie values from the controller to view, I must do that for each of my action and I don't prefer it. Also it will make more complex code.
I saw this question and that question. (Also it is possible to read them with $_COOKIE[<cookie_name>], but that solution can't be used for encrypted cookies. My cookie is not encrypted but it can be in future)
My question is why there is no CookieHelper in the Cake's libs ? Is that a bad practice to reach cookies from the view files ? Is there a methodical way to reach cookies from views ? For example writing a custom helper that uses $_COOKIE and use that helper ?
Passing the data from the controller is an appropriate way of doing this.
If you need the data in many/all views, use the Controller::beforeFilter() callback, that way the variable is available to all views rendered by the specific controller:
class MyController extends AppController
{
// ...
public function beforeFilter()
{
parent::beforeFiler();
$this->set('cookie', $this->Cookie->read('cookie'));
}
// ...
}
Just make sure that possible cookie component configuring is done before reading the cookie!
I believe you can access it via the SessionHelper:
echo $this->Session->read($cookieName);
You can read cookie by help of javascript if this does not work use ajax calls to read cookies on document load and implement your logic by returning via json.
I am very new to CakePHP and the whole MVC framework. My question is where is the best place to incorporate sessions in my website.
I want to start a session as soon as a user visits the site and check if it is valid and if the user is logged in (via a session attribute) before each call to a controller.
Should I be placing the logic to check for a valid session in the AppController? if so how can I do that because nothing instantiates the AppController so I cannot use $this->html->session().
Many Thanks
You are on the right track, but take another look at the documentation on Sessions.
You want to be using $this->Session->read/write/check/etc
Cakephp will always start a session if you've included the Session component and for the most part this is exactly what you want. In the AppController you only need to tell CakePHP to use the Session component.
Something like this...
public $components = array(
'Session',
'RequestHandler',
'Cookie'
);
And then include the helper as well...
public $helpers = array('Html', 'Form', 'Session');
Now you're ready to rock.
To store a value in the session :
$this->Session->write("myvalue");
to read a value from the session:
$this->Session->read("myvalue");
You can also check if a value is set using :
$this->Session->check("myvalue");
You can also use beforeFilters in your controller to block access to the controller:
public function beforeFilter(){
parent::beforeFilter();
if(!$this->Session->check("id")){
$this->redirect("/users/login");
}
}
Alternatively just wrap the above in a private method and call the method on the first line of all the actions you want to control access to.
Is there an Auth Component's helper in Cakephp 2.x?
Currently I just pass the $Auth object to the view in the AppController like so:
$this->set('Auth', $this->Auth);
I searched around but there doesnt seem to be a helper available by default. I need some of the functions of the Auth component in the views like Auth::loggedIn().
help?
There is no need for an AuthHelper
The AuthComponent::user function can be called statically:
if (AuthComponent::user()) {
// user is logged in
}
Or since it just reads from the session the same information can also be found via the session (component/helper/class):
if ($this->Session->read('Auth.User')) {
// user is logged in
}
It is not a good idea, or required to pass the Auth component (or any component) to the view.
The Auth Component still exists: http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html
I have a controller that is called with AJAX (sends JSON data), so I don't use a view.
I need to use a personnal view helper to format my data, but in my controller.
Is that possible ?
Or maybe I am doing it wrong (maybe I should have a view, but how with JSON) ?
You can access any ViewHelper from the Controller by
$this->view->helpername(/*params*/);
// or
$helper = $this->view->getHelper('helpername');
// or
$broker = Zend_Controller_Action_HelperBroker::getStaticHelper('ViewRenderer');
$broker->getView()->helpername(/*params*/);
See Zend: How to use a custom function from a view helper in the controller?
However, you might be right that you are doing it wrong (funny pic btw), but I cannot really tell from your question. Please refine it as to why you need to call the view helper and what it is supposed to format.
Zend_Controller_Front::getInstance()->getParam('bootstrap')->getResource('view');
Just be sure that the returned view is the view you want. Because down the line, the view may get overwritten and on the controller you have a spank new view.
And all those values you setup on the view on the action helper and the like... before the controller is kicked in? All gone with the wind!
So test before assuming that if you get a view resource. it is really the same view resource you expect, and that all your vars are still there.
You may be surprised as i was!
You can create an instance of a Helper .. this will work in Controllers, Models and everywhere you need the Helper.
eg.
// create Instance
$serverUrl_helper = new Zend_View_Helper_ServerUrl();
// get the ServerUrl
$serverUrl = $serverUrl_helper->serverUrl();
Another approach is to use the ContextSwitch or AjaxContext action-helpers. This allows you to use a view-script from which you can then call your view-helper in the standard manner.
Just use action helpers, many of view helpers are available as action helpers too.
Or directly by using Zend_Date or sprintf.
Can you tell me how to use a controller for home page because i'm trying to put a model's data in home.ctp (homepage view) with
<?php $this->user->find() ?>but it returns
Notice (8): Undefined property:
View::$user [APP\views\pages\home.ctp,
line 1]
You should check out the cookbook; it has some solid CakePHP tutorials, at http://book.cakephp.org/
You haven't really provided alot of information, but my guess is your Controller uses a model 'User', and you're putting $this->user->find() in your view, when it should be in your controller. In your controller's action you'll want/need to do something like this...
Users_Controller extends AppController {
function index() {
$arrayOfUsers = $this->User->find(...);
$this->set('users', $arrayOfUsers);
}
}
You can then - in your View - access 'users' like so:
pre($users);
... since you used the Controller method set() to send a variable $users to the view.
All you really need to do is create a new controller if that's the direction you want to go. If this is the only statement you have that requires data access, it might be worth faking it in only this method of the PagesController. For example, one of my projects' homepages is 99% static save for a list of featured events. Rather than move everything out to a new controller or even loading my Event model for the entire PagesController (where it's not needed), I just applied this solution in PagesController::home():
$attractions = ClassRegistry::init ( 'Attraction' )->featured ( 10 );
Works great. If your page is more dynamic than mine, though, it may well be worth routing your homepage through a different controller (one that is more closely related to the data being displayed).
The default controller for the home page i.e home.ctp view, is located in /cake/libs/controller/pages_controller.php. This controller can be overriden by placing a copy in the controllers directory of your application as /app/controllers/pages_controller.php. You can then modify that controller as deem fit i.e. use models, inject variables to be used in the home page etc