Sometimes during development or customization in Magento 2, you may have some cases where you need to check if a module is enabled or disabled.
In this article, we will show you how to Check If Module is Enabled or Disable Programmatically 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\Framework\Module\Manager as ModuleManager;
class MyModel
{
/**
* @var ModuleManager
*/
protected $moduleManager;
/**
* @param ModuleManager $moduleManager
*/
public function __construct(
ModuleManager $moduleManager
) {
$this->moduleManager = $moduleManager;
}
/**
* Check if the module is enabled
*
* @param string $moduleName Fully-qualified module name . eg. 'Magento_Csp'
* @return bool
*/
public function isModuleEnabled($moduleName)
{
return $this->moduleManager->isEnabled($moduleName);
}
}
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);
}
/**
* Check if the module is enabled
*
* @param string $moduleName . eg. 'Magento_Csp'
* @return bool
*/
public function isModuleEnabled($moduleName)
{
return $this->myModel->isModuleEnabled($moduleName);
}
}
replace: Vendor\Module with your vendor and module name
3. Using PHTML
In the phtml template file, you can call your isModuelEnabled() method from your custom block Vendor\Module1\Block\MyBlock
Example:
<?php
$moduleName = 'YOUR MODULE NAME'; // eg. Magento_Csp, or Vendor_MyModule
?>
<?= $block->escapeHtml($block->isModuleEnabled($moduleName)) ?>
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)