5

I want the replacement of the following code or similar to this code to get all category and subcategory in Magento 2.

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

any help will be appreciated

Thanks.

Manish
  • 3,106
  • 7
  • 31
  • 47

3 Answers3

7

1 – Create you new Extension for our case in folder

app/code/Ibnab/CategoriesSide

and inside etc folder declare you etc declare module.xml and di.xml with content : module.xml :

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../lib/internal/Magento/Framework/Module/etc/module.xsd">
    <module name="Ibnab_CategoriesSide" setup_version="1.0.0" schema_version="1.0.0">
        <sequence>
            <module name="Magento_Catalog"/>
        </sequence>
    </module>
</config>

 di.xml :
 <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../lib/internal/Magento/Framework/ObjectManager/etc/config.xsd">
    <type name="Ibnab\CategoriesSide\Block\CategorisCollection">
        <arguments>
            <argument name="deleteorderAction" xsi:type="array">
                <item name="context" xsi:type="string">\Magento\Framework\View\Element\Template\Context</item>
                <item name="helper" xsi:type="string">\Magento\Catalog\Helper\Category</item>
                <item name="flatstate" xsi:type="string">\Magento\Catalog\Model\Indexer\Category\Flat\State</item>
               <item name="menu" xsi:type="string">\Magento\Theme\Block\Html\Topmenu</item>
            </argument>
        </arguments>
    </type>
</config>

Note - Here the dependency is for inject the class \Magento\Catalog\Helper\Category for getting all categories of current store (And OR ) get the top menu html for the complete collection you need inject \Magento\Theme\Block\Html\Topmenu , 2 - the injection is for our data source the block Ibnab\CategoriesSide\Block\CategorisCollection create and put the code :

<?php
namespace Ibnab\CategoriesSide\Block;
class CategorisCollection extends \Magento\Framework\View\Element\Template
{
     protected $_categoryHelper;
     protected $categoryFlatConfig;
     protected $topMenu;
    /**
     * @param \Magento\Framework\View\Element\Template\Context $context
     * @param \Magento\Catalog\Helper\Category $categoryHelper
     * @param array $data
     */
    public function __construct(
        \Magento\Framework\View\Element\Template\Context $context,
        \Magento\Catalog\Helper\Category $categoryHelper,
        \Magento\Catalog\Model\Indexer\Category\Flat\State $categoryFlatState,
        \Magento\Theme\Block\Html\Topmenu $topMenu
    ) {
        $this->_categoryHelper = $categoryHelper;
        $this->categoryFlatConfig = $categoryFlatState;
        $this->topMenu = $topMenu;
        parent::__construct($context);
    }
    /**
     * Return categories helper
     */   
    public function getCategoryHelper()
    {
        return $this->_categoryHelper;
    }
    /**
     * Return top menu html
     * getHtml($outermostClass = '', $childrenWrapClass = '', $limit = 0)
     * example getHtml('level-top', 'submenu', 0)
     */   
    public function getHtml()
    {
        return $this->topMenu->getHtml();
    }
    /**
     * Retrieve current store categories
     *
     * @param bool|string $sorted
     * @param bool $asCollection
     * @param bool $toLoad
     * @return \Magento\Framework\Data\Tree\Node\Collection|\Magento\Catalog\Model\Resource\Category\Collection|array
     */    
   public function getStoreCategories($sorted = false, $asCollection = false, $toLoad = true)
    {
        return $this->_categoryHelper->getStoreCategories($sorted , $asCollection, $toLoad);
    }
    /**
     * Retrieve child store categories
     *
     */ 
    public function getChildCategories($category)
    {
           if ($this->categoryFlatConfig->isFlatEnabled() && $category->getUseFlatResource()) {
                $subcategories = (array)$category->getChildrenNodes();
            } else {
                $subcategories = $category->getChildren();
            }
            return $subcategories;
    }
}

Note – The more important here is getStoreCategories and getChildCategories($category) , it get you the data collection tree from helper , and getHtml() is return the complete collection is more quick for correct the html 3 - ok now create you template inside view/frontend/template/storecategories.phtml with content :

<?php
$categories = $this->getStoreCategories(true,false,true);
$categoryHelper = $this->getCategoryHelper();
?>
<ul>
<?php
foreach($categories as $category):
     if (!$category->getIsActive()) {
        continue;
     }
?>
<li><a href="<?php echo $categoryHelper->getCategoryUrl($category) ?>"><?php echo $category->getName() ?></a></li>
<?php  
if($childrenCategories = $this->getChildCategories($category)):
?>
<ul>
<?php
foreach($childrenCategories as $childrenCategory):
     if (!$childrenCategory->getIsActive()) {
        continue;
     }
?>
<li><a href="<?php echo $categoryHelper->getCategoryUrl($childrenCategory) ?>"><?php echo $childrenCategory->getName() ?></a></li>
<?php
endforeach;
?>
</ul>
<?php
endif;
endforeach;
?>
</ul>
<h1>OR Just</h1>
<?php echo $this->getHtml() ?>

For more detail see here.

enter preformatted text here

Arunendra
  • 7,446
  • 3
  • 29
  • 54
4
<?php
 $catId =2;
        $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
        $subcategory = $objectManager->create('Magento\Catalog\Model\Category')->load($catId);           
        $subcats = $subcategory->getChildrenCategories();
        ?>
        <ul >
            <li> <span> All Categories </span> </li>
            <?php
            foreach ($subcats as $subcat) {
                if ($subcat->getIsActive()) {

                    $subcat_url = $subcat->getUrl();
                    $subcat_img = "";
                    $placeholder_img = "/media/placeholder.png";
                    ?>
                    <li>
                        <a href="<?php echo $subcat_url; ?>">
                            <?php echo $subcat->getName(); ?>
                        </a>
                    </li>

                    <?php
                }
            }
            ?>
        </ul>
Raphael at Digital Pianism
  • 70,385
  • 34
  • 188
  • 352
Harsha
  • 49
  • 1
4

Magento 2.2.3

Get all Subcategories base on current category.

    $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
    $category = $objectManager->get('Magento\Framework\Registry')->registry('current_category');//get current category    


    $catId =$category->getId();        
    $subcategory = $objectManager->create('Magento\Catalog\Model\Category')->load($catId);           
    $subcats = $subcategory->getChildrenCategories();
    ?>
    <ul >
        <?php
        foreach ($subcats as $subcat) {
            if ($subcat->getIsActive()) {

                $subcat_url = $subcat->getUrl();
                $subcat_img = "";
                $placeholder_img = "/media/placeholder.png";
                ?>
                <li>
                    <a href="<?php echo $subcat_url; ?>">
                        <?php echo $subcat->getName(); ?>
                    </a>
                </li>

                <?php
            }
        }
        ?>
    </ul>