Call-back icon  Enterprise Sales: +1.310.775.2674 (N. America)   +44 20.3286.4137 (UK)

Magento

eCommerce Software for Online Growth

Magento Forum

   
Page 1 of 2
Subcategories for a parent category
 
Steve P. Sharpe
Jr. Member
 
Total Posts:  11
Joined:  2008-06-01
 

Hi all,

I need to be able to pull of a list of subcategories for a specified parent category id. For example I have two main categories setup (Departments & Flavours) on every page I want to show all of the subcategories for these main categories.

I see there is a getCurrentChildCategories function, which is kind of what I need but like this getChildCategories(4) - 4 being the parent id.

Hopefully that makes sense and what I’m asking is quite simple? I’ve searched the forum for a while and can’t find an answer.

Thanks in advance
Steve P. Sharpe

 
Magento Community Magento Community
Magento Community
Magento Community
 
Anders Rasmussen
Guru
 
Avatar
Total Posts:  343
Joined:  2007-10-16
Denmark
 

I guess you can just copy the function, rename it to getChildCategories($parentId), and replace $category = $layer->getCurrentCategory(); with $category = Mage::getModel(’catalog/category’)->load($parentId);

 Signature 

Anders Rasmussen
Crius (in Danish)

 
Magento Community Magento Community
Magento Community
Magento Community
 
Steve P. Sharpe
Jr. Member
 
Total Posts:  11
Joined:  2008-06-01
 

Hi there,

I tried that, but got an error. However it did point me in the right direction. So thank-you!

For those that are interested this is what I did which is based on the getStoreCategories function.

left.phtml - 6 is the id of the parent category

<ul>
<?php foreach ($this->getSubCategories(6) as $_category): ?>
    <?php 
echo $this->drawItem($_category?>
<?php 
endforeach ?>
</ul>

/Mage/Catalog/Model/Category.php

public function getSubCategories($parentId)
    
{
        $helper 
Mage::helper('catalog/category');
        return 
$helper->getSubCategories($parentId);
    
}

/Mage/Catalog/Helper/Category.php

public function getSubCategories($parentId$sorted=false$asCollection=false$toLoad=true)
    
{
        $category 
Mage::getModel('catalog/category');
        
/* @var $category Mage_Catalog_Model_Category */
        
if (!$category->checkId($parentId)) {
            
if ($asCollection{
                
return new Varien_Data_Collection();
            
}
            
return array();
        
}

        $tree 
$category->getTreeModel();
        
/* @var $tree Mage_Catalog_Model_Resource_Eav_Mysql4_Category_Tree */

        
$nodes $tree->loadNode($parentId)
            ->
loadChildren()
            ->
getChildren();

        
$tree->addCollectionData(null$sorted$parentId$toLoadtrue);

        if (
$asCollection{
            
return $tree->getCollection();
        
else {
            
return $nodes;
        
}
    }

Hopefully this helps someone?

 
Magento Community Magento Community
Magento Community
Magento Community
 
ayayaaa
Jr. Member
 
Total Posts:  5
Joined:  2008-06-27
 

Hi,

I put this function in navigation.php and it works.

public function getSubCategories($parentId)
    
{
    
        $helper 
Mage::helper('catalog/category');
        return 
$helper->getSubCategories($parentId);
    
}

Thanks for your code

 
Magento Community Magento Community
Magento Community
Magento Community
 
toadx
Jr. Member
 
Total Posts:  21
Joined:  2008-06-19
 

It helped me a lot.  Thank you greatly my friend.

 
Magento Community Magento Community
Magento Community
Magento Community
 
Hengky Irawan
Jr. Member
 
Avatar
Total Posts:  10
Joined:  2008-05-25
Indonesia
 

Hi,

Thank you for your code. It works like charm.
But, one question, how do I get the current parent category ID ?

Calviin

 Signature 

there’s no such thing as a coincidence. everything happens for a reason

 
Magento Community Magento Community
Magento Community
Magento Community
 
pdxwebhead
Jr. Member
 
Total Posts:  27
Joined:  2008-07-16
Portland Oregon
 

I’m trying to figure out how to apply this code to a left-nav example.. Where do I put put these code snippets to have a vertical nav display the child categories, or child products directly underneath the parent category when parent is selected ?

 Signature 

Learning Magento one mistake at a time....

 
Magento Community Magento Community
Magento Community
Magento Community
 
brad_frost
Jr. Member
 
Total Posts:  18
Joined:  2008-06-27
 

Hi, I am trying to implement Steve’s code and it is returning a PHP error:

WarningInvalid argument supplied for foreach()  in .../httpdocs/app/design/frontend/kirna_zabete/clothes_subcats/template/catalog/navigation/left.phtml on line 35

Here’s what I have implemented for left.phtml

<ul>
<?php foreach ($this->getSubCategories(3) as $_category): ?>
    <?php 
echo $this->drawItem($_category?>
<?php 
endforeach ?>
</ul>

Is there any specific place in each of the Category.php files where I need to place the respective functions? Can anyone offer some advice?

Thanks very much

 
Magento Community Magento Community
Magento Community
Magento Community
 
dcorrell
Jr. Member
 
Total Posts:  18
Joined:  2008-07-28
 

i get the same error as brad, any suggestions?

 
Magento Community Magento Community
Magento Community
Magento Community
 
win_
Sr. Member
 
Total Posts:  82
Joined:  2008-02-24
Cape Town, South Africa
 

I have got this working by doing the following:

in my template folder in app/design/frontend/default/mytheme/template/catalog/navigation I created a new file called: vert_nav.phtml
and referenced this file in my catelog.xml file

<?php
/**
 * Magento
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the Open Software License (OSL 3.0)
 * that is bundled with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://opensource.org/licenses/osl-3.0.php
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@magentocommerce.com so we can send you a copy immediately.
 *
 * @category   design_default
 * @package    Mage
 * @copyright  Copyright (c) 2004-2007 Irubin Consulting Inc. DBA Varien (http://www.varien.com)
 * @license    http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
 */
?>
<?
/**
 * Category left navigation
 * 
 * @see Mage_Catalog_Block_Navigation
 */
?>
<?
$_categories
=$this->getCurrentChildCategories()
?>
<?if
($_categories->count()):?>

    
<h3><?=$this->__('Shop by')?> Category</h3>
        <
ul>
               
<?foreach ($_categories as $_category):?>
                <?if
($_category->getIsActive()):?>
                    
<li><a href="<?=$this->getCategoryUrl($_category)?>"<?if ($this->isCategoryActive($_category)):?> class="active"<?endif?>><?=$_category->getName()?></a> (<?=$_category->getProductCount()?>)</li>
                
<?endif;?>
            <?endforeach?>
                        
         
        
</ul>


<?else:
    
//No sub categories? Get the parent category and show that menu instead
    
$_currentCateogry Mage::registry('current_category');
    if (
$_currentCateogry{
        
        $path 
$_currentCateogry->getPathInStore();
        
$pathIds array_reverse(explode(','$path));
        
$categories Mage::getResourceModel('catalog/category_collection')
            ->
addAttributeToSelect('name')
            ->
addAttributeToSelect('url_key')
            ->
addFieldToFilter('entity_id', array('in'=>$pathIds))
            ->
load()
            ->
getItems();
        
        
// add category path breadcrumb
       
        
foreach ($pathIds as $categoryId{
            
if ($categories[$categoryId]->getName() != Mage::registry('current_category')->getName()){
                $_parentCateogry 
$categories[$categoryId];
                
//echo $_parentCateogry;
                
//we grab the id of the parent category with the next line
                
$id=Mage::getBlockSingleton('catalog/navigation')->getCurrentCategory()->parent_id
                
$_categories=$this->getSubCategories($id);
                
                if(
$_categories->count()) {
                    ?>
                    
<h3><?=$this->__('Shop by')?> Category</h3>
                        <
ul>
                            
<?foreach ($_categories as $_category):?>
                                <?if
($_category->getIsActive()):?>
                                    
<li><a href="<?=$this->getCategoryUrl($_category)?>"<?if ($this->isCategoryActive($_category)):?> class="active"<?endif?>><?=$_category->getName()?></a></li>
                                
<?endif;?>
                            <?endforeach?>
                                        
                        
</ul>
                       
<?
                }
            }
        }
    }
    
?>



<?endif
;?>
<!-- [ends] .browse-by // -->

then I added the following code to app/code/core/Mage/Catalog/Block/Navigation.php

//get subcategories 
    public function getSubCategories($parentId)
    
{
        $helper 
Mage::helper('catalog/category');
        return 
$helper->getSubCategories($parentId);
    
}

I also added the following code to app/code/core/Mage/Catalog/Model/Category.php

//get the category parent id
    public function getSubCategories($parentId)
    
{
        $helper 
Mage::helper('catalog/category');
        return 
$helper->getSubCategories($parentId);
    
}

and I also added the following code to app/code/core/Mage/Catalog/Helper/Category.php

//get category parent id
    public function getSubCategories($parentId$sorted=false$asCollection=false$toLoad=true)
    
{
        $category 
Mage::getModel('catalog/category');
        
/* @var $category Mage_Catalog_Model_Category */
        
if (!$category->checkId($parentId)) {
            
if ($asCollection{
                
return new Varien_Data_Collection();
            
}
            
return array();
        
}

        $tree 
$category->getTreeModel();
        
/* @var $tree Mage_Catalog_Model_Resource_Eav_Mysql4_Category_Tree */

        
$nodes $tree->loadNode($parentId)
            ->
loadChildren()
            ->
getChildren();

        
$tree->addCollectionData(null$sorted$parentId$toLoadtrue);

        if (
$asCollection{
            
return $tree->getCollection();
        
else {
            
return $nodes;
        
}
    }

This solution prints out the sub categories of my parent category and it’s working sweet!
Just remember to make the changes in the local folder so that your changes won’t get overwrite with the next upgrade

Hope this helps some peeps out there,

Happy Friday,

Wins

 
Magento Community Magento Community
Magento Community
Magento Community
 
device55
Jr. Member
 
Total Posts:  6
Joined:  2008-03-08
Portland, OR
 

I tried this technique and it worked beautifully. Thanks for posting it.

Following the recommendation in the last post, I extended the core classes, and created directories for them in my /app/code/local directory

This resulted in the following files:
/app/code/local/[Foo]/Catalog/Block/Navigation.php
/app/code/local/[Foo]/Catalog/Helper/Category.php
/app/code/local/[Foo]/Catalog/Model/Category.php

With the following class names:
Foo_Catalog_Block_Navigation
Foo_Catalog_Helper_Category
Foo_Catalog_Model_Category

The extended classes are very simple, only containing the additional methods, like so:

/**
 * Catalog navigation
 *
 * @category   Foo
 * @package    Foo_Catalog
 * @author     You
 */
class Foo_Catalog_Block_Navigation extends Mage_Catalog_Block_Navigation
{

    
/**
     * Get sub categories by parent ID
     *
     * @param int $parentId 
     * @return void
     * @author You
     */
    
public function getSubCategories($parentId)
    
{
        $helper 
Mage::helper('catalog/category');
        return 
$helper->getSubCategories($parentId);
    
}

}
/**
 * Catalog category helper
 *
 * @category   Foo
 * @package    Foo_Catalog
 * @author      you
 */
class Foo_Catalog_Helper_Category extends Mage_Catalog_Helper_Category
{

    
/**
     * get category parent id
     *
     * @param int $parentId 
     * @param bool $sorted 
     * @param bool $asCollection 
     * @param bool $toLoad 
     * @return void
     * @author you
     */
    
public function getSubCategories($parentId$sorted=false$asCollection=false$toLoad=true)
    
{
        $category 
Mage::getModel('catalog/category');
        
/* @var $category Mage_Catalog_Model_Category */
        
if (!$category->checkId($parentId)) {
            
if ($asCollection{
                
return new Varien_Data_Collection();
            
}
            
return array();
        
}

        $tree 
$category->getTreeModel();
        
/* @var $tree Mage_Catalog_Model_Resource_Eav_Mysql4_Category_Tree */

        
$nodes $tree->loadNode($parentId)
            ->
loadChildren()
            ->
getChildren();

        
$tree->addCollectionData(null$sorted$parentId$toLoadtrue);

        if (
$asCollection{
            
return $tree->getCollection();
        
else {
            
return $nodes;
        
}
    }
}
/**
 * Catalog category
 *
 * @category   Foo
 * @package    Foo_Catalog
 * @author      you
 */
class Foo_Catalog_Model_Category extends Mage_Catalog_Model_Category
{
    
/**
     * Get SubCategories by id
     *
     * @param int $parentId 
     * @return void
     * @author you
     */
    
    
public function getSubCategories($parentId)
    
{
        $helper 
Mage::helper('catalog/category');
        return 
$helper->getSubCategories($parentId);
    
}
    
}

To activate these classes add the following to your /app/etc/local.xml file, between the <global> tags:

<blocks>
                 <
catalog>
                     <
rewrite>
                         <
navigation>Foo_Catalog_Block_Navigation</navigation>
                     </
rewrite>
                 </
catalog>
                    </
blocks>
                    <
helpers>
                        <
catalog>
                            <
rewrite>
                                <
category>Foo_Catalog_Helper_Category</category>
                            </
rewrite>
                        </
catalog>
                    </
helpers>
                    <
models>
                        <
catalog>
                            <
rewrite>
                                <
category>Foo_Catalog_Model_Category</category>
                            </
rewrite>
                        </
catalog>
                    </
models>

Update: I added the other two classes to my code samples above, in case anyone wants to copy them. Remember “Foo” should be the namespace for your project, so the parent directory “Foo” should be renamed as well as the first part of each class name.

 Signature 

-O^O-

 
Magento Community Magento Community
Magento Community
Magento Community
 
win_
Sr. Member
 
Total Posts:  82
Joined:  2008-02-24
Cape Town, South Africa
 

any way to extend this script to print out sub categories in a separate <ul> so that we can use it with jQuery accordion?
any help would be much appreciated,

win

 
Magento Community Magento Community
Magento Community
Magento Community
 
device55
Jr. Member
 
Total Posts:  6
Joined:  2008-03-08
Portland, OR
 

You may want to look at the Mage_Catalog_Block_Navigation::drawItem() method - and creating a new method based upon it - to render out an unordered list which highlights the current category by css class name.

See [theme folder]/template/catalog/navigation/top.phtml for usage.

That should provide you with enough HTML / CSS hooks to let jQuery expand or collapse the resulting menu.

 Signature 

-O^O-

 
Magento Community Magento Community
Magento Community
Magento Community
 
Armen
Member
 
Total Posts:  42
Joined:  2008-05-06
Los Angeles
 

This is excellent guys! Thanks for sharing this code. I had to write up the config.xml myself but that wasn’t so hard to figure out after following the examples here…

http://www.magentocommerce.com/wiki/groups/174/changing_and_customizing_magento_code

Also I think I remember reading in another thread that you can’t extend the same class twice with two different extensions. Without looking that up to see if I was 100% correct, and knowing that Rico’s VertNav extension already extends Mage_Catalog_Block_Navigation, I just added the new public function for the Block extension in his existing file. This would probably give me trouble after upgrading his extension but I am sure I can quickly add it again.

 
Magento Community Magento Community
Magento Community
Magento Community
 
madla
Jr. Member
 
Total Posts:  18
Joined:  2009-03-29
 

Unfortunately this is no longer working in 1.3.1.

It errors out in getSubCategories function at:
$tree->addCollectionData(null, $sorted, $parentId, $toLoad, true);

with an error of:

PHP Fatal error:  Call to undefined method Mage_Catalog_Model_Resource_Eav_Mysql4_Category_Flat_Collection::getAllIdsSql() in /Applications/MAMP/htdocs/magento/app/code/core/Mage/Catalog/Model/Resource/Eav/Mysql4/Category/Tree.php on line 224

Does anybody have an idea what to do about it?

Thanks...martin

 
Magento Community Magento Community
Magento Community
Magento Community
 
lakanat
Jr. Member
 
Total Posts:  10
Joined:  2009-04-05
 

Hi ,

exactly the same result with 13.1

Fatal error: Call to undefined method Mage_Catalog_Model_Resource_Eav_Mysql4_Category_Flat_Collection::getAllIdsSql() in /var/clients/client7/web9/web/app/code/core/Mage/Catalog/Model/Resource/Eav/Mysql4/Category/Tree.php on line 224

working in progress ...

 
Magento Community Magento Community
Magento Community
Magento Community
Magento Community
Magento Community
    Back to top
Page 1 of 2
 
© Copyright 2009 Varien. Magento, eCommerce software, is a trademark of Irubin Consulting Inc. DBA Varien
Privacy Policy|Terms of Service
Magento Community Count
108673 users|386 users currently online|199750 forum posts