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

12,113

Solution 1

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.

Solution 2

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);
}
Share:
12,113

Related videos on Youtube

geoffs3310
Author by

geoffs3310

Professional web developer for a multi-national, multi-million dollar company. Proficient in PHP, OOPHP, cakePHP, XHTML, CSS, Javascript, jQuery, Drupal, Wordpress.

Updated on June 04, 2022

Comments

  • geoffs3310
    geoffs3310 almost 2 years

    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?

Related