1

After extending a controller in magento2 via a module, I realized that disabling it on a per website basis wouldn't be possible using the module disable method in the backend. Any advice on how to achieve this when a module extends a controller?

3

I would create a Store Configuration value to disable your functionality. This way you can have a flag which disables the module only for one store or website.

For example, create a new Store configuration value:

<vendor>/<module>/etc/adminhtml/system.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Config:etc/system_file.xsd">
    <system>
        <tab id="mymodule" translate="label" sortOrder="100">
            <label>My Module</label>
        </tab>
        <section id="mymodule" translate="label" type="text" sortOrder="100" showInDefault="1" showInWebsite="1" showInStore="1">
            <label>My Module</label>
            <tab>myconfig</tab>
            <resource>Vendor_Module::system_config</resource>
            <group id="general" translate="label" type="text" sortOrder="1" showInDefault="1" showInWebsite="1" showInStore="1">
                <label>General Configuration</label>
                <field id="enable" translate="label" type="select" sortOrder="10" showInDefault="1" showInWebsite="1" showInStore="1">
                    <label>Enable Module</label>
                    <source_model>Magento\Config\Model\Config\Source\Enabledisable</source_model>
                </field>
            </group>
        </section>
    </system>
</config>

Then you can use this value in your code:

class Myclass
{
    public function __construct(
        \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig
    ){
        $this->scopeConfig = $scopeConfig;
    }

    public function isModuleEnabled($website = null)
    {
        return $this->scopeConfig->isSetFlag(
            'mymodule/general/enable',
            \Magento\Store\Model\ScopeInterface::SCOPE_WEBSITE,
            $website
        );
    }

    public function execute()
    {
        if ($this->isModuleEnabled()) {
            // Do stuff here if module is enabled.
        }
    }
}

You will have a core config value that you can set to Enable for one website, and set it to Disable for another.

1
  • Hi, just came across this answer and I thought to do the same thing, but it's complicated when you have many controllers and views as well, in an existing module. Is there one overriding controller that can be created to set this for all others? – Ynhockey Aug 6 '18 at 14:51

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.