2

How to get root category using store id. we get store id using $storeId = $this->getStoreId(); We use below code for get root category using store id; but we get wrong.

$rootCat = $this->_storeManager->getStore($storeId)->getRootCategoryId();

Any one help us for solve this.

  • No; we want store root category; which is assign in 'Store > Setting > All store > Here select any store > you show 'Root Category'. – Anil May 22 at 11:36
4

You can use \Magento\Store\Model\StoreManagerInterface class to get store default root category Id.

<?php
class Test
{
    /**
     * @var \Magento\Store\Model\StoreManagerInterface
     */
    protected $storeManagerInterface;

    public function __construct(\Magento\Store\Model\StoreManagerInterface $StoreManagerInterface)
    {
         $this->storeManagerInterface = $StoreManagerInterface;
    }



    public function getRootCategoryId()
    {
        $store = 1;
        return $this->storeManagerInterface->getStore($store)->getRootCategoryId();
    }

}
  • We use it but not work for me – Anil May 22 at 11:43
  • what problem you are facing – surbhi agr May 22 at 11:46
  • Admin side page break; get error page can't reach. Not generate any error in log file. – Anil May 22 at 11:47
1

I think something like this


namespace MyCompany\MyModule\Block;

class MyModel extends \Magento\Framework\View\Element\Template
{
    protected $_storeManager;    

    public function __construct(
        \Magento\Backend\Block\Template\Context $context,        
        \Magento\Store\Model\StoreManagerInterface $storeManager,        
        array $data = []
    )
    {        
        $this->_storeManager = $storeManager;        
        parent::__construct($context, $data);
    }

    /**
     * Get store identifier
     *
     * @return  int
     */
    public function getStoreId()
    {
        return $this->_storeManager->getStore()->getId();
    }

    /**
     * Get root category id for current store
     *
     * @return  int
     */

    public function getRootCategoryId()
    {
        return $this->storeManagerInterface->getStore($this->getStoreId())->getRootCategoryId();
        // or return $this->_storeManager->getStore()->getRootCategoryId();
    }
}

So in your block template phtml you will use

$block->getRootCategoryId();
  • Page break in admin; page show 'This page isn’t working'. – Anil May 22 at 12:06

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.