William
William

Reputation: 4588

Cake PHP multiple view pages have access to the same variables

I'm doing the blog tutorial (CakePHP 2.4.1) and have a question.

What is the reasoning ( and why) does the index.ctp page require me to loop through the $posts variable to get data but the view.ctp file lets me just grab $post without looping? I deleted the following action in PostController.php and still could render the view.ctp file so I figure the two are not connected.

 public function index() {
    $this->set('posts', $this->Post->find('all'));
}

Upvotes: 0

Views: 369

Answers (2)

Ryan Tuosto
Ryan Tuosto

Reputation: 1951

    $this->set('posts', $this->Post->find('all')); 

This will return an array of posts - notice the find('all')

    $this->set('post', $this->Post->findById($id));

This will return a single post by the passed $id parameter.

The reason you have to loop through $posts is because its an array (returned by the find all), where $post is just a single post returned by findById)

Upvotes: 0

Nick Savage
Nick Savage

Reputation: 876

You're setting post in both of the controller's functions:

index()

$this->set('posts', $this->Post->find('all'));

view()

$post = $this->Post->findById($id);
$this->set('post', $post);

It would be odd if you weren't able to access the variables, but it seems everything is functioning as normal in your example

Edit:

You loop through the array in the index because you have multiple posts inside of an array. And in the view you're setting only a singular array containing one post so there is no need to loop through anything, you're able to grab the elements directly.

Upvotes: 2

Related Questions