Magento 2 – Disable Module and Its Output Programmatically

configurationmagento-2.0magento2module

In magento 1 disable module and it's output programmatically

protected function _disableModule($moduleName) {
    // Disable the module itself
    $nodePath = "modules/$moduleName/active";
    if (Mage::helper('core/data')->isModuleEnabled($moduleName)) {
        Mage::getConfig()->setNode($nodePath, 'false', true);
    }

    // Disable its output as well (which was already loaded)
    $outputPath = "advanced/modules_disable_output/$moduleName";
    if (!Mage::getStoreConfig($outputPath)) {
        Mage::app()->getStore()->setConfig($outputPath, true);
    }
}

How can I do same in magento 2?

Best Answer

To disable a module itself, you need to use Magento\Framework\Module\Status class:

$status = $this->objectManager->create('Magento\Framework\Module\Status');
$status->setIsEnabled(false,[$moduleName]);

To disable the module output, you need to use Magento\Config\Model\ResourceModel\Config via the factory Magento\Config\Model\ConfigFactory:

$outputPath = "advanced/modules_disable_output/$moduleName";
$config = $this->objectManager->create('Magento\Config\Model\ResourceModel\Config');
$config->saveConfig($outputPath,true,'default',0);

In the line, default corresponds to the scope and 0 to the scope id. Those values will have to be changed depending on your needs.

N.B. : this code is provided as a quick example, try to avoid using the object manager directly and use dependency injection to use those classes

Related Topic