Cakephp - one variable accessible in view and controller

11,602

Solution 1

$this->set('arr', array('one', 'two'));

// Accessible in controller as 
$this->viewVars['arr'];

// Accessible in view/layout as
echo $arr;

Solution 2

If you set any variable in AppController beforeRender() function,and set that variable,then you can access easily that variable anywhere in the view files

function beforeRender() {
    parent::beforeRender();
    $sample_arr = array("abc","xyz");
    $this->set('sample_arr',$sample_arr);
}

In your Layout File Just Print that Array like

print_r($sample_arr);
Share:
11,602
Piotr Łużecki
Author by

Piotr Łużecki

I am lazy javascript developer.

Updated on June 22, 2022

Comments

  • Piotr Łużecki
    Piotr Łużecki almost 2 years

    I want to define an array which I can use in AppController and in the default layout.

    How can I do this in CakePHP?

  • Vishal Kumar Sahu
    Vishal Kumar Sahu almost 7 years
    Is it safe to go like that?
  • Neo Anderson
    Neo Anderson over 3 years
    in CakePhp4 replaced with this : $this->viewBuilder()->getVar('arr');