How to get a list of items from a category to show on a single page cakephp

1k views Asked by At

I am having problems trying to get my cake application to display items from the database on a single page based on the url of the page... For example I want to display items that are in the "Party" category and I type "mydomain.com/All/party" in the address bar and I get a list of all the items in that category on that page.

This is my code but the pages I am getting from the route is blank:

My routes.php:

    Router::connect('/categories/:name', array(
   'controller' => 'All', 'action' => 'categories'
),
array(
    'pass' => 'catname',
    'catname' => '[a-zA-Z0-9]+'
));

my AllController.php:

    function categories($catname = null) {
$options = array(
    'conditions' => array('Category.name'=>$catname)
);
$Category = $this->Category->find('all', $options);
$this->set('Category', $Category);
$this ->render('/All/categories');
}

Any help would be appreciated.

3

There are 3 answers

2
José Lorenzo Rodríguez On

I don't get at all the code you just posted, but what you want to achieve is quite trivial:

Router::connect(
    '/products/:category', 
    ['controller' => 'products', 'action' => 'categorized'], 
    ['pass' => ['category']]
);

In ProductsController:

function categorized($category) {
    $conditions = ['Category.name' => $category];
    $this->set('products', $this->Prodcut->find('all', compact('conditions')));
}

That's it. You may want to reuse the index action if you don't need a separate view template for that, in that case just set the conditions (for example to the Paginator component) and call $this->setAction('index')

0
Horace Mozadegh-Khorampast Cun On

I found a much easier way to do what I wanted. I just remember that I had a database search option that allows persons to search for products and categories. What I did was simply do a search for the categories and then copy the URL of the page I got and set that as a link to the category in my application.

Example code:

<ul class="filter-options">
  <li><a style="color:#fff" href="http://mydomain.com/products/search?q=parties">Parties</a></li>
  <li><a style="color:#fff" href="http://mydomain.com/products/search?q=festivals">Festivals</a></li>
  <li><a style="color:#fff" href="http://mydomain.com/products/search?q=theatres">Cinemas/Theatres</a></li>

0
Nabila On

Everything looks good on your side just change your routes.php as follows

Router::connect('/categories/:catname', array(
        'controller' => 'all', 
        'action' => 'categories'),
            array('pass' => array('catname'),
                'catname' => '[a-zA-Z0-9]+'));