Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set a variable in the app_controller and use it in a CakePHP layout

I need to set a variable in the app_controller of CakePHP and then use it in my default layout file.

Is there a way to set this variable?

like image 769
geoffs3310 Avatar asked Jan 05 '11 10:01

geoffs3310


2 Answers

I think what he meant was, that he doesn't know where to set a variable since he's not in a specific function inside a controller. To have a variable (or anything else really) available everywhere, you have to put it in your AppController like this:

function beforeFilter()
  {
  $this->set('whatever', $whatever);
  }

More on those callback functions here.

like image 175
pawelmysior Avatar answered Sep 18 '22 02:09

pawelmysior


The callback functions in AppController are the place to $this->set() variables that you want available to all of your views and layouts. beforeFilter() is called before all controller actions. If you want to set a view variable after an action has run, use beforeRender(). You can access your other view variables in the $this->viewVars associative array.

function beforeRender() {
    $new = "Universal " . $this->viewVars['layoutTitle']; 
    $this->set('universalTitle', $new);
}
like image 45
JCotton Avatar answered Sep 18 '22 02:09

JCotton