Passing data to the view

Published on and tagged with cakephp  controller  tip  view

If you want to pass data from the controller to the view, you usually use something like:

$this->set('key', 'value');

Not really new, is it? What’s less known is that you can use an array syntax:

$this->set(array('key1' => 'value1', 'key2' => 'value2'));

As you would expect, the keys are available as $key1 resp. $key2 in the view.

6 comments baked

  • KesheR

    baking arrays, as usual :D

  • Tijs

    Another neat trick is to use the compact function to throw a bunch of stuff together in a single set:

    $post = $this->Post->read();
    $comments = $this->Comments->findById($post[‘Post’][‘id’]);
    $someString = “hello world!”;

    $this->set(compact(‘post’, ‘comments’, ‘someString’));

  • ryan

    very nice… useful post, and useful comment by Tijs – i definitely wasn’t aware of either of these methods… thanks guys!

  • cakebaker

    @Tijs: Thanks for the additional tip.

    @ryan: I am glad this post was useful for you.

  • Dat Chu

    Also, can someone confirm this: $this->data ALWAYS get pass to the view when it gets rendered, so there is no need to reassign them.

    If this is true, you can do (I think):
    $this->data = $this->Post->read();
    array_push($this->data, $this->Comment->findAll());

  • Dat Chu

    Nevermind my comment above, $this->data can only be accessed via $html helpers

Bake a comment




(for code please use <code>...</code> [no escaping necessary])

© daniel hofstetter. Licensed under a Creative Commons License