views:

103

answers:

1

Hi, i've been triyng to change the default result page of magento, i want the products grouped by categories, it don't include the subcategories but the products, the search criteria is the product name, so, i was triyng to use the defalt simple search of magento, untill now no result, maybe i have to override the search and make a new one, i know that with this i can get all the categories and its product collection,

$categories = Mage::getModel('catalog/category')
->getCollection()
->addAttributeToSelect('*');    

foreach($categories as $category)
{
    $array = $category->getParentIds();
    $children = explode(',',$category->getChildren());
    $products = $category->getProductCollection();
}

but i need to filter by the produc name, the result i'm secting to show is like this

Category I  
    - Product I  
    - Product II  
Category II  
    - Product III  
    - Product IV  
A: 

after a few days coding i was able to get a list of categories with child products, i'm going to share my code, maybe it would help someone

public function getProducts(){
    $categories=Mage::getModel('catalog/category')->getCollection();
    $result;
    foreach($categories as $cat)
    {
        $temp = null;
        $_temp = null;
        $are = false;
        $_cat = $cat->load();
        $temp['category'] = $_cat->getName();
        $prod = $_cat->getProductCollection()
                     ->addAttributeToFilter('name', array('like'=>'%'.$this->getRequest()->getParam('q').'%'));
        foreach($prod as $p){
            //die(print_r($p->load()));
            $_temp[] = $p->load();
            $are = true;
        }
        if($are){
            $temp[] = $_temp;
            $result[] = $temp;
        }
    }
    return $result;
}

i put this function in a block in my custom module, this function return an array with another array in each position, then in a .phtml file you can loop like this

<?php $productsResult = $this->getProducts();
if(count($productsResult)+count($prodnorelatedResult)>0){ ?>
    <h2>Products</h2>
        <?php foreach($productsResult as $p){ ?>
    <h3><?php echo $p['category'] ?></h3>
    <?php foreach($p[0] as $_p){ ?>
        <div><a href="<?php echo $_p->getProductUrl()?>"><?php echo $_p->getName() ?></a></div><br/>
    <?php } ?>
    <br/>
<?php } } ?>

this is just an example where i show the name of the category with his products name as a link to the product detail page

hope it help

Kstro21