Vael Victus
Vael Victus

Reputation: 4122

CakePHP: Send all variables to an element from within another element

Imagine I have a very complex app. I have a controller that calls characters.ctp. Lots of DB work is done here for all the "characters".

Within characters.ctp, I call the monsters element. It prints out a monster and gives me the relevant info for the monsters, retrieved from the DB. Now within the monsters element, I want to make another element for invertebrates because they're so complex that they require lots of new view elements and CSS.

invertebrates does not carry the scope of monster's variables it inherited through $this->set() from the controller. How can I send all variables to the child-element of an element? I'm using cake 2.8.4.

Upvotes: 0

Views: 203

Answers (1)

Fouss
Fouss

Reputation: 71

Using the set() method inside your element

With all the DB work done in the characters controller, you should do some controller job inside monster by re-setting the variables carried by monster using View::set :

# /app/View/Elements/monster.ctp

//if you want to set variables one by one
$this->set('varForInvertebrates', $varForMonster);

//if you want to set an array of variables
$this->set(array(
    'var1' => $var1,
    'var2' => $var2,
    ...
));

And if you still need data from a controller

If you have to compute data available in monster in order to use it in invertebrates, you can use CakeObject::requestAction to explicitly call a controller :

# /app/View/Elements/monster.ctp

// if the controller returns a variable
$this->set('varForInvertebrates', $this->requestAction('controller/method/param1/param2'));

// if the controller returns an array of variables
$this->set($this->requestAction('controller/method/param1/param2'));

Upvotes: 1

Related Questions