Sunday, November 15, 2009

How to List Posts by Categories

There's a lot to bake with Cake. I'm entering into deeper domains. I hope you are also following me.
Today, I'll show you how to list posts by categories. To do so, we will use 'containable' behavior.

Edit Category Model
file:// app/models/category.php
Replace:
var $actsAs = array('Tree');
With
var $actsAs = array('Tree','Containable');
Notice I have added the word 'Containable' in the $actsAs behavior.

Add  listposts() 'action' in Category Controller
file:// app/controllers/categories_controller.php

function listposts() {


$listPosts = $this->Category->find('all');
$this->set(compact('listPosts'));
}
Create a  VIEW file for showing query result.
file:// app/views/categories/listposts.ctp



<h1>Posts found by category</h1>
  <?php
  foreach ($listPosts as $key => $value) {
    
   echo "<h3>" . $value["Category"]["name"] .   "</h3>";
  $posts = $value["Post"];
   foreach ($posts as $post) {
    echo "<b>" . $post["title"] . "</b>";
    echo "<br />";
   }
   }
  ?>


Now point your browser to:
http://caketest.local/categories/listposts


You should see something like this:



That's it!

No comments: