I created a page using the MVC structure called 'sections' ( view is located in the app/views/sections folder, model in the model folder and the controller in the controller 开发者_JAVA技巧folder) when i request the variable $test, it works fine without any errors..
When i want to request this variable in my home.ctp, it provides me with an error, saying that the variable is undefined..
Is there any way in cakePHP to request this variable on any page you want it to?
Thnx in advance!
In the MVC stack, you need to set variables with data in your controller, and then pass them out to your view.
So in your example, you'll want to $this->set('myvar',$item);
in your SectionsController
, then in your view, you will be able to echo $myvar
.
Be sure to set this in the home()
method of your Sections
controller, otherwise it won't be available in your home
view.
Standing on the shoulders of deceze's comment and DavidYell's answer, I think they've managed to scratch out a decent view of what you're trying to get to. Maybe. So with that loose understanding of what you're seeing and what you have...
By default, the PagesController::display()
method generates the homepage view (home.ctp
). I suspect that this is what you're talking about. That said, the variable you're setting in a method of your SectionsController
won't be available to your homepage which is created by a different method in a different controller. If you want a variable available to all views there are several things you can do:
- You can set the variable in your
config/core.php
file (not generally recommended) - You can set it in
config/bootstrap.php
if it's a constant. By that, I mean that it's a value you're going to hard code, not something dynamically generated. Whether you create the variable as a constant doesn't matter. - You can set in in your
AppController
in abeforeFilter()
orbeforeRender()
method. All of your custom controllers (assuming you've followed protocol) inherit from theAppController
. If you choose this path, make a copy ofcake/libs/controller/app_controller.php
and place it in yourapp/
directory.
Those are the ways that I think will best meet your needs as I understand them.
精彩评论