10

I want to display categories tree on frontend like admin default categories tree.

Need to display category tree structure in my custom module and content area for frontend side.

Any Help would be appreciated.

Thanks.

4

1) go to "app" from root directory of Magento 2 and create new directory code. Then create two more directories in app/code, Namespace and Module Name. The final directory will look like this: app/code/Demo/CategoryTree.

Demo as Namespace and CategoryTree as module name.

2) create "module.xml" file in app/code/Demo/CategoryTree/etc and paste below code into the file:

<?xml version="1.0"?>
<!--
/**
 * Copyright © 2013-2017 Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */
-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
    <module name="Demo_CategoryTree" setup_version="1.0.0">
        <sequence>
            <module name="Magento_Catalog"/>
        </sequence>
    </module>
</config>

3) create "route.xml" file in app/code/Demo/CategoryTree/etc/frontend and paste below code into the file:

<?xml version="1.0"?>
<!--
/**
 * Copyright © 2013-2017 Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */
-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">
    <router id="standard">
        <route id="categorytree" frontName="categorytree">
            <module name="Demo_CategoryTree" />
        </route>
    </router>
</config>

4) create "registration.php" file in app/code/Demo/CategoryTree and paste below code in file:

<?php
/**
 * Copyright © 2013-2017 Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::MODULE,
    'Demo_CategoryTree',
    __DIR__
);

5) create "Index.php" file in app/code/Demo/CategoryTree/Controller/Index and paste below code into the file:

<?php
/**
 *
 * Copyright © 2013-2017 Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */
namespace Demo\CategoryTree\Controller\Index;

class Index extends \Magento\Framework\App\Action\Action
{
    /**
     * @var \Magento\Framework\View\Result\PageFactory $resultPageFactory
     */
    protected $resultPageFactory;

    /**
     * @param \Magento\Framework\App\Action\Context $context
     * @param \Magento\Framework\View\Result\PageFactory $resultPageFactory
     */
    public function __construct(
        \Magento\Framework\App\Action\Context $context,
        \Magento\Framework\View\Result\PageFactory $resultPageFactory
    ) {
        $this->resultPageFactory = $resultPageFactory;
        parent::__construct($context);
    }

    /**
     * Renders CATEGORYTREE Index page
     *
     * @param string|null $coreRoute
     * @return \Magento\Framework\Controller\Result\Forward
     * @SuppressWarnings(PHPMD.UnusedFormalParameter)
     */
    public function execute($coreRoute = null)
    {
        $resultPage =  $this->resultPageFactory->create();
        $resultPage->getConfig()->getTitle()->set(__('CategoryTree'));
        return $resultPage;
    }
}

6) create "categorytree_index_index.xml" file in app/code/Demo/CategoryTree/view/frontend/layout and paste below code into the file:

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="2columns-left" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <update handle="styles"/>
    <head>
        <css src="extjs/resources/css/ext-all.css"/>
        <css src="extjs/resources/css/ytheme-magento.css"/>
    </head>
    <body>
        <referenceContainer name="sidebar.additional">
            <block class="Magento\Catalog\Block\Adminhtml\Category\Tree" name="category.tree" template="Demo_CategoryTree::catalog/category/tree.phtml"/>
        </referenceContainer>
    </body>
</page>

7) copy from vendor/magento/module-catalog/view/adminhtml/templates/catalog/category/tree.phtml to app/code/Demo/CategoryTree/view/frontend/templates/catalog/category

8) create "requirejs-config.js" file in app/code/Demo/CategoryTree/view/frontend and paste below code into the file:

var config = {
    "shim": {
        "extjs/ext-tree": [
            "prototype"
        ],
        "extjs/ext-tree-checkbox": [
            "extjs/ext-tree",
            "extjs/defaults"
        ]
    }
};

9) Run below commands in the root directory:

php bin/magento setup:upgrade
php bin/magento cache:clean
php bin/magento cache:flush
php bin/magento setup:static-content:deploy

10) run url like this "http://local-magento.com/categorytree/index/index" so you will get output like below.

enter image description here

1

Okay this is what I use to generate a menu based on my category tree. It should be noted that for ease all my categories are stored under the default category with ID2, that comes with a fresh install of Magento2. If you do not have this structure, you could alternatively define $soncats as an array of the IDs of categories you would like to loop through instead.

<ul id="nav" class="accordion vertnav vertnav-top grid-full wide">
    <?php
$fathercat = $objectManager->create('Magento\Catalog\Model\Category')->load(2); //this is my master root category, holds all other categories so I can loop through.
$soncats = $fathercat->getChildrenCategories(); 
$catids = array(2); 
foreach ($soncats as $soncat) {
    $categoryid = $soncat->getId();
    array_push($catids,$categoryid);
}
for($i = 1; $i < count($catids); ++$i) { 
    $basic = 1;
    $catId = $catids[$i];
    $subcategory = $objectManager->create('Magento\Catalog\Model\Category')->load($catId);
    $subcats = $subcategory->getChildrenCategories();
    $categoryname = $subcategory->getName(); 
    $categoryurl = $subcategory->getUrl(); ?>
    <li class="level0 nav-<?php echo $i;?> level-top parent"><a href="<?php echo $categoryurl ?>" class="level-top"><?php echo $categoryname; ?><span class="caret"> </span> </a><span class="opener"> </span>
        <div class="level0-wrapper dropdown-6col" style="left: 0;">
            <div class="level0-wrapper2">
                <ul class="level0 part">
                    <?php
                    foreach ($subcats as $subcat) { 
                        if ($subcat->getIsActive()) {
                            $subcat_url = $subcat->getUrl(); 
                            $subcat_name = $subcat->getName(); ?>
                            <li class="level1 nav-1-<?php echo $basic;?> item"><a href="<?php echo $subcat_url ?>"><?php echo $subcat_name; ?></a></li>
                            <?php
                        } $basic++; } ?>
                    </ul>
                </div>
            </div>
        </div>
    </li>
    <?php } ?>
</ul>
  • Hello John, it seems like you have undefined variable $addedq. – Purushotam Sangroula Jan 5 '18 at 9:42
  • Hi Anime, thank you for spotting that, addedq was another variable previously defined and relative to my project in question, it is not necessary for the code to work – John Jan 5 '18 at 10:25
  • this code is not display child's sub categories – HaFiz Umer Jul 11 at 8:01
  • @HaFizUmer thats strange because it should be, but also I wouldn't be surprised because it's for Magento 2.0~. It may need modifying/rewriting for anything Magento 2.1+ – John Jul 12 at 7:19

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.