1

In a Magento 2 multistore, is there a way to create a module available for one particular store only?

I know that I can disable a module using the admin, but that only disables the output of it. Is it possible to add some kind of rule into module.xml or something like that to limit the scope of the module?

3

No, there is no rule you can set in module.xml to have a module enabled in one store only but you can do this:
Create an enabled/disabled setting in system.xml in your module.

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Config:etc/system_file.xsd">
    <system>
        <section id="your_module_name">
            <group id="settings" translate="label" sortOrder="1000" showInDefault="1" showInWebsite="1" showInStore="1">
                <label>MOdule settings</label>
                <field id="enable" translate="label" type="select" sortOrder="1" showInDefault="1" showInWebsite="1" showInStore="0" canRestore="1">
                    <label>Enable My module</label>
                    <source_model>Magento\Config\Model\Config\Source\Yesno</source_model>
                </field>
             </group>
         </section>
    </system>
</config>

Then in your class methods (not sure which ones because I don't know how your module works) do this:
First add \Magento\Framework\App\Config\ScopeConfigInterface as a dependency to your class:

protected $scopeConfig;

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

And for your methods that interact with Magento somehow (for example a frontend controller action, or an observer) you can do this:

public function someMethodNameHere($parametersHere)
{
    if (!$this->scopeConfig->isSetFlag('your_module_name/settings/enable', \Magento\Store\Model\ScopeInterface::SCOPE_STORE)) {
         return 'some default value goes here. Can be null, a string, an array, ....';
    }
    //your custom code for the method goes here.
}
  • I suggest providing the third parameter on the isSetFlag() call to make sure the correct store id is used. Otherwise it falls back on the StoreManager to provide it, which might or might not use the store id you think it would (for example if you place an order from the admin for a certain store you might have store id = 0 instead of store id = 1 that you were expecting) – Kristof at Fooman Dec 5 '16 at 23:22
  • 1
    @Marius that's great, thank you. I thought it would be some kind of rule because I remember there was something similar in Magento 1 (something like <restricted>store_code</restricted>). – pinicio Dec 7 '16 at 22:11

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.