0

I have to load the category collection and show it on top menu position on my Magento site. I have tried object manager concept but it's not correct method to follow so that I have to load it using dependency injection.

I have referred this http://www.blogtreat.com/how-to-get-category-collection-in-magento-2/, but I don't know where to use this and how to show it on frontend since I'm new in Magento.

Can anyone please help me?

  • Hi @Siva, At first you should try to create a custom module. It will help you. – Ramkishan Suthar Sep 22 at 6:06
  • Yes, i understand that I have to create custom module, my question is how to show that in top menu position? – Siva Sep 22 at 6:12
  • Did you find the file for top position? Or can you please show me with screen shot where you want to put that categories? – Mayur Sep 23 at 2:45
  • @Mayur, I have managed to get the result. Now, I have to load sub category. Can you please help me on this? – Siva Sep 23 at 4:14
  • Shall I give in answer for subcategory? – Mayur Sep 23 at 4:33
0

Create Custom module with your PackageName and ModuleName

1.Create a registration.php file at

PackageName/ModuleName/registration.php

Add below code

<?php
\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::MODULE,
    'PackageName_ModuleName',
    __DIR__
);

2.Create a module.xml file at

PackageName/ModuleName/etc/module.xml

Add below code

<config xsi:noNamespaceSchemaLocation="../../../../../lib/internal/Magento/Framework/Module/etc/module.xsd">
<module name="PackageName_ModuleName" setup_version="1.0.0"/>
</config>

3.Create a CategoriesList.php file at

PackageName\moduleName\Block\CategoriesList.php

Add below code

<?php
namespace PackageName\moduleName\Block;
class CategoriesList extends \Magento\Framework\View\Element\Template
{    
    protected $_categoryCollectionFactory;
    protected $_categoryHelper;

    public function __construct(
        \Magento\Backend\Block\Template\Context $context,        
        \Magento\Catalog\Model\ResourceModel\Category\CollectionFactory $categoryCollectionFactory,
        \Magento\Catalog\Helper\Category $categoryHelper,
        array $data = []
    )
    {
        $this->_categoryCollectionFactory = $categoryCollectionFactory;
        $this->_categoryHelper = $categoryHelper;
        parent::__construct($context, $data);
    }

    public function getCategoryCollection($isActive = true, $level = false, $sortBy = false, $pageSize = false)
    {
        $collection = $this->_categoryCollectionFactory->create();
        $collection->addAttributeToSelect('*');        

        if ($isActive) {
            $collection->addIsActiveFilter();
        }

        if ($level) {
            $collection->addLevelFilter($level);
        }


        if ($sortBy) {
            $collection->addOrderField($sortBy);
        }


        if ($pageSize) {
            $collection->setPageSize($pageSize); 
        }    

        return $collection;
    }


    public function getStoreCategories($sorted = false, $asCollection = false, $toLoad = true)
    {
        return $this->_categoryHelper->getStoreCategories($sorted = false, $asCollection = false, $toLoad = true);
    }
}
?>

4.Create topmenu.phtml tempate file at

PackageName/ModuleName/view/frontend/templates/html/topmenu.phtml

Add below code

<ul class="your-class">
 <?php /* @escapeNotVerified */ echo $_menu; ?>

    $categories = $block->getCategoryCollection(); 
    foreach ($categories as $category) {
        //print_r($category->getData());
        echo $category->getName() . '<br />';
    }

    // get categories sorted by category 'name'
    $categories = $block->getCategoryCollection(true, false, 'name', false);
    foreach ($categories as $category) {    
        echo $category->getName() . '<br />';
    }

    // get current store's categories
    $categories = $block->getStoreCategories();
    foreach ($categories as $category) {    
        echo $category->getName() . '<br />';
    }
</ul>

5.Create default.xml layout file at (render your template at top menu postion )

PackageName/ModuleName/view/frontend/layout/default.xml

Add below code

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceBlock name='catalog.topnav'>
                <action method='setTemplate'>
                        <argument name='template' xsi:type='string'>PackageName_ModuleName::html/topmenu.phtml</argument>
                </action>
        </referenceBlock>
    </body>
</page>

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.