0

I'd like to list all first level categories from inside my custom block. I'd like to get the category names and the URLs.

How can I achieve this?

1

Try:

/** @var \Magento\Catalog\Model\ResourceModel\Category\Collection $collection */
$collection = $this->collectionFactory->create();
$collection->addFieldToFilter('level', 2);
$collection->addIsActiveFilter();
$collection->setStoreId($storeId);
$collection->addUrlRewriteToResult();
$collection->addAttributeToSelect('name');

Where $storeId is your current store id. You can get it by

// \Magento\Store\Model\StoreManagerInterface $storeManager,
$storeId = $this->storeManager->getStore()->getId();

[Update]

Sample block class:

<?php


namespace VendorName\Checkout\Block;

use Magento\Catalog\Helper\Category;
use Magento\Catalog\Model\ResourceModel\Category\StateDependentCollectionFactory;
use Magento\Framework\View\Element\Template;
use Magento\Store\Model\StoreManagerInterface;

class Test extends Template
{
    /**
     * @var Category
     */
    private $catalogCategory;

    /**
     * @var StateDependentCollectionFactory
     */
    private $collectionFactory;

    /**
     * @var StoreManagerInterface
     */
    private $storeManager;

    /**
     * Test constructor.
     * @param Template\Context $context
     * @param Category $catalogCategory
     * @param StateDependentCollectionFactory $categoryCollectionFactory
     * @param StoreManagerInterface $storeManager
     * @param array $data
     */
    public function __construct(
        Template\Context $context,
        Category $catalogCategory,
        StateDependentCollectionFactory $categoryCollectionFactory,
        StoreManagerInterface $storeManager,
        array $data = []
    ) {
        $this->catalogCategory = $catalogCategory;
        $this->collectionFactory = $categoryCollectionFactory;
        $this->storeManager = $storeManager;
        parent::__construct($context, $data);
    }

    public function getCategories()
    {
        $storeId = $this->storeManager->getStore()->getId();
        /** @var \Magento\Catalog\Model\ResourceModel\Category\Collection $collection */
        $collection = $this->collectionFactory->create();
        $collection->addFieldToFilter('level', 2);
        $collection->addIsActiveFilter();
        $collection->setStoreId($storeId);
        $collection->addUrlRewriteToResult();
        $collection->addAttributeToSelect('name');

        $categories = [];
        foreach ($collection as $category) {
            $categories[] = [
                'name' => $category->getName(),
                'url' => $this->catalogCategory->getCategoryUrl($category)
            ];
        }

        return $categories;
    }
}
7
  • Hello, sorry if its a silly question, but how can I get $storeId ? – Vibhore Jain Jul 22 at 5:09
  • check the updated answer – Sohel Rana Jul 22 at 5:11
  • @VibhoreJain please check my Answer, here you can get whole code magento.stackexchange.com/a/341568/82670 – Msquare Jul 22 at 6:07
  • @SohelRana thanks but could you elaborate this? How should I create my block class? – KaMZaTa Jul 22 at 11:35
  • Check the updated answer. You should call $block->getCategories() from your phtml template that is related to this block class – Sohel Rana Jul 22 at 11:47
0

Try this code

protected $_storeManager;
protected $categoryRepository;

public function __construct(
    \Magento\Store\Model\StoreManagerInterface $storeManager,
    \Magento\Catalog\Model\CategoryRepository $categoryRepository
) {
    $this->_storeManager = $storeManager;
    $this->categoryRepository = $categoryRepository;
}

public function getFirstCategoryIds()
{
    $categoryId = $this->_storeManager->getStore()->getRootCategoryId();
    $category = $this->categoryRepository->get($categoryId, $this->_storeManager->getStore()->getId());
    foreach ($category->getChildrenCategories() as $key => $value) {
        $categoryData = $this->getCategoryData($value->getEntityId());
        print_r($categoryData->getName());
        echo " -- " . $categoryData->getUrl();
        echo "<br/>";
    }
    return $category->getChildrenCategories();
}

public function getCategoryData($id)
{
    return $this->categoryRepository->get($id, $this->_storeManager->getStore()->getId());
}

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.