Sometimes during development or customization in Magento 2, you may have some cases where you need to get all root categories Ids.
In this article, we will show you how to How to get all Root Categories ids in Magento 2.
1. Using Model
This class Magento\Framework\Module\Manager in Magento 2 includes the isEnabled method to check if the module is enabled.
You can create your custom model Vendor\Module\Model\MyConfig where you check if the module is enabled or disabled, and use it further when needed in your code.
<?php
namespace Vendor\Module\Model;
use Magento\Store\Model\StoreManagerInterface;
class MyModel
{
/**
* @var StoreManagerInterface
*/
protected $storeManagerInterface;
/**
* @param StoreManagerInterface $storeManagerInterface
*/
public function __construct(
StoreManagerInterface $storeManagerInterface
) {
$this->storeManagerInterface = $storeManagerInterface;
}
/**
* Return ids of root categories as an array
*
* @return array
*/
public function getRootCategoryIds()
{
$ids = [\Magento\Catalog\Model\Category::TREE_ROOT_ID];
foreach ($this->storeManagerInterface->getGroups() as $store) {
$ids[] = $store->getRootCategoryId();
}
return $ids;
}
}
2. Using Block
You can inject your custom model Vendor\Module\Model\MyModel in your block to check if the module is enabled or disabled.
Example:
<?php
namespace Vendor\Module\Block;
use Magento\Framework\View\Element\Template;
use Magento\Framework\View\Element\Template\Context;
use Vendor\Module\Model\MyModel;
class MyBlock extends Template
{
/**
* @var MyModel
*/
protected $myModel;
/**
* @param Context $context
* @param MyModel $myModel
* @param array $data
*/
public function __construct(
Context $context,
MyModel $myModel,
array $data = []
) {
$this->myModel = $myModel;
parent::__construct($context, $data);
}
/**
* Return ids of root categories as an array
*
* @return array
*/
public function getRootCategoryIds()
{
return $this->myModel->getRootCategoryIds();
}
}
replace: Vendor\Module with your vendor and module name
3. Using PHTML
In the phtml template file, you can call your getRootCategoryIds() method from your custom block Vendor\Module1\Block\MyBlock
Example:
<?= $block->escapeHtml($block->getRootCategoryIds()) ?>
if you print_r getRootCategoryIds method in your template file, it may give output as follow :
Array
(
[0] => 1
[1] => 2
[2] => 3
)
In the outputs above:
1 is your Root Catalog id,
2 is your Default Category id.
3 is your custom-created root category id.
Conclusion
We hope you find this guide to "Check If Module is Enabled or Disable In Magento 2" helpful. Feel free to share or leave a comment below. Your opinion is much appreciated!
If you're looking for experienced Magento 2 developers to customize your site, fix issues, develop custom solutions, support, maintain, or anything else, feel free to check on this collection of Quality Services For Magento 2, choose the service that best suits your requirements, or contact us
0 Comment(s)