5

Magento 2 Display Sub Category of parent? I am trying to get subcategory using current category registry object but i don't know how to getChildrenCategories for parent.

7

My code to get the category list for the main category is:

public function __construct(
        Template\Context $context, 
        \Magento\Catalog\Model\Layer\Resolver $layerResolver, 
        \Magento\Framework\Registry $registry, 
        \Magento\Catalog\Helper\Category $categoryHelper, 
        \Magento\Catalog\Model\CategoryFactory  $categoryFactory,
        array $data = array()) 
    {
        parent::__construct($context, $layerResolver, $registry, $categoryHelper,$data);
        $this->_categoryFactory = $categoryFactory;
        $this->_collectionFactory = $collectionFactory;
     }

    public function getCategoryList()
    {
      $_category  = $this->getCurrentCategory();
      $collection = $this->_categoryFactory->create()->getCollection()->addAttributeToSelect('*')
              ->addAttributeToFilter('is_active', 1)
              ->setOrder('position', 'ASC')
              ->addIdFilter($_category->getChildren());
      return $collection;

    }
  • where did you add this code? – Jimmery Apr 26 '16 at 13:56
  • in block file you have any issue? – Pratik Apr 27 '16 at 5:01
4

For reference you can start with core files See vendor/magento/module-catalog/Block/Navigation.php

getCurrentChildCategories() function:

$categories = $this->_catalogLayer->getCurrentCategory()->getChildrenCategories();

Where getCurrentCategory simply fetches current category from registry just like you did. So getChildrenCategories should work for you.

Also, more functions related to child/sub-categories are available in this file. vendor/magento/module-catalog/Model/Category.php . So if you get category object you can fetch sub-category data from it by using any of the functions defined in this file, as per your requirement.

Hope this helps!!

2

In your theme add the following to the appropriate container in your app/design/frontend/YourNamespace/YourTheme/layout/catalog_category_view.xml layout file.

<block class="Magento\Catalog\Block\Navigation"
           name="catalog.subnav"
           after="-"
           template="Magento_Catalog::category/category-subnav.phtml"/>

Then create a new file in app/design/frontend/YourNamespace/YourTheme/Magento_Catalog/templates/category/category-subnav.phtml and add the following.

<?php if (!$block->getCategory()) {
    return;
} ?>
<?php $_categories = $block->getCategory()->getParentCategory()->getChildrenCategories(); ?>
<?php $_count = is_array($_categories) ? count($_categories) : $_categories->count(); ?>
<?php if ($_count): ?>
    <div class="block subnav">
        <div class="content">
            <ol class="items">
                <?php foreach ($_categories as $_category): ?>
                    <?php if ($_category->getIsActive()): ?>
                        <li class="item">
                            <a href="<?php /* @escapeNotVerified */ echo $block->getCategoryUrl($_category) ?>"<?php if ($block->isCategoryActive($_category)): ?> class="current"<?php endif; ?>><?php echo $block->escapeHtml($_category->getName()) ?></a>
                        </li>
                    <?php endif; ?>
                <?php endforeach ?>
            </ol>
        </div>
    </div>
<?php endif; ?>

This should give you a list containing the current category and its siblings/child.

1

code for get subcategory from category id

class Test{

  public function __construct(
        \Magento\Catalog\Model\Category $categoryFactory
    )
    {
     $this->_categoryFactory = $categoryFactory;
    }
 $catId = 20;
 public function getsubCategories($catId){
    $cat = $this->_categoryFactory->load($catId);
    $subcats = $cat->getChildren();
    $subcategories = array();
    foreach(explode(',',$subcats) as $subCatid){
        $_subCategory = $this->_categoryFactory->load($subCatid);
        if($_subCategory->getIsActive()) {
            $subcategories[] = array('id'=>$_subCategory->getId(),'name'=>$_subCategory->getName()); 
        }
    }
    return $subcategories; 
}
0

Use below code to get all active child categories of a specific category.

Function getChildCategories($categoryId) gives all child categories. Where $categoryId - is parent category id

<?php
namespace YourModuleName\CategoryLink\Block;

use Magento\Framework\View\Element\Template;
use Magento\Framework\View\Element\Template\Context;
use Magento\Catalog\Model\CategoryFactory;


/**
 * Category link block
 */
class Link extends Template
{
    /**
     * @var Magento\Catalog\Model\CategoryFactory
     */
    protected $_categoryFactory;


    /**
     * 
     * @param Context $context
     * @param array $data
     */
    public function __construct(
        Context $context, 
        CategoryFactory $categoryFactory,
        array $data = []
    ) {
        parent::__construct($context, $data);
        $this->_categoryFactory = $categoryFactory;
      }

    /**
     * Get children categories 
     * 
     * @param $categoryId Parent category id
     * @return Magento\Catalog\Model\ResourceModel\Category\Collection
     */
    public function getChildCategories($categoryId)
    {

        $_category = $this->_categoryFactory->create();

        $category = $_category->load($categoryId);

        //Get category collection
        $collection = $category->getCollection()
                ->addIsActiveFilter()
                ->addOrderField('name')
                ->addIdFilter($category->getChildren());
        return $collection;
    }

} 

$category->getChildren() - This will gives all chid categories ids.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.