0

I am a beginner in Magento. This may be a simple question.

I have a header menu 'shop'. This link should redirect to a page that shows all parent categories. How can I do this? any help is really appreciated.

This is how the 'shop' page should looks like (Parent categories only).

This what I need

Thank you.

17
  • Yes I can help you. Jan 20, 2020 at 11:30
  • Could you please tell me how can I do this ?
    – Sayanth
    Jan 20, 2020 at 12:57
  • you can see here..magento.stackexchange.com/questions/300734/… Hope my answer will help you! Jan 20, 2020 at 14:02
  • Could you please tell me how to set the phtml file ? I am totally confused with the magento workflow
    – Sayanth
    Jan 20, 2020 at 14:06
  • yes so in which page you need all display Jan 20, 2020 at 16:17

2 Answers 2

0

Please try this code.

$objectManager =  \Magento\Framework\App\ObjectManager::getInstance();        


$categoryFactory = $objectManager->get('\Magento\Catalog\Model\CategoryFactory');
$categoryHelper = $objectManager->get('\Magento\Catalog\Helper\Category');
$categoryRepository = $objectManager->get('\Magento\Catalog\Model\CategoryRepository');

$categoryId = 3; // YOUR CATEGORY ID
$category = $categoryFactory->create()->load($categoryId);

//var_dump($category->getData());

$parentCategories = $category->getParentCategories();
$childrenCategories = $category->getChildrenCategories();
$subcats = $childrenCategories->getData();

foreach ($childrenCategories as $cat) {
    echo $cat->getName();
    echo "<br>";
}

and then use it in your .phtml file. Hope it works!

0

You can try this code:

first you create a category source file inside Model:

Note: Here root categories are excluded.

path: Vendor\ModuleName\Model\Source\Categories.php

Categories.php

<?php

namespace Vendor\ModuleName\Model\Source;

class Categories implements \Magento\Framework\Option\ArrayInterface {

    protected $_categoryFactory;
    protected $_categoryCollectionFactory;

    public function __construct(
       \Magento\Catalog\Model\CategoryFactory $categoryFactory,
       \Magento\Catalog\Model\ResourceModel\Category\CollectionFactory $categoryCollectionFactory
    ) {
        $this->_categoryFactory = $categoryFactory;
        $this->_categoryCollectionFactory = $categoryCollectionFactory;
    }

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

        // select only active categories
        if ($isActive) {
            $collection->addIsActiveFilter();
        }

        // select categories of certain level
        if ($level) {
            $collection->addLevelFilter($level);
        }

        // sort categories by some value
        if ($sortBy) {
            $collection->addOrderField($sortBy);
        }

        // select certain number of categories
        if ($pageSize) {
            $collection->setPageSize($pageSize);
        }

        $this->excludeRootCategories($collection, $excludeLevel);

        return $collection;
    }

    public function toOptionArray() {
        return $arr = $this->_toArray();
    }

    private function _toArray() {
        $categories = $this->getCategoryCollection(false, false, false, false);

        $catagoryList = array();
        foreach ($categories as $category) {
            $catagoryList[] = ['label' => __($this->_getParentName($category->getPath()) . $category->getName()), 'value' => $category->getEntityId()];
        }

        return $catagoryList;
    }

    private function _getParentName($path = '') {
        $parentName = '';
        $rootCats = array(1, 2);

        $catTree = explode("/", $path);
        // Deleting category itself
        array_pop($catTree);

        if ($catTree && (count($catTree) > count($rootCats))) {
            foreach ($catTree as $catId) {
                if (!in_array($catId, $rootCats)) {
                    $category = $this->_categoryFactory->create()->load($catId);
                    $categoryName = $category->getName();
                    $parentName .= $categoryName . ' -> ';
                }
            }
        }

        return $parentName;
    }

    public function excludeRootCategories($collection, $excludeLevel) {
        $collection->addFieldToFilter('level', ['gteq' => $excludeLevel]);
        return $this;
    }

    public function getCategoriesOptionsArray() {
        $categories = $this->getCategoryCollection(true, 2, false, false, 2);

        $catagoryList = array();
        foreach ($categories as $category) {
            $catagoryList[] = ['label' => __($this->_getParentName($category->getPath()) . $category->getName()), 'value' => $category->getEntityId()];
        }

        return $catagoryList;
    }

}

Now you need to call the categories model class in your block file:

.........
protected $_categoriesSource;
.........

public function __construct(
        ..........
        \Vendor\ModuleNAme\Model\Source\Categories $categoriesSource, 
        ..........
) {
    ......
    $this->_categoriesSource = $categoriesSource;
    ......
}

public function getParentCategoryOptions() {
    return $this->_categoriesSource->getCategoriesOptionsArray();
}

finally, you can get the lists of all parent categories in phtml file:

$categoryOptions = $block->getParentCategoryOptions();
echo '<pre>';
print_r(categoryOptions);

Hope, this solution will help you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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