Magento 2 Custom Module – Add Enable/Disable Field

extensionsmagento-2.1magento2modulePHP

I want to add some fields in the Magento 2 Admin Panel for my custom module and then I want to check in the phtml file if this field is have value or not.

I need to add this fields:

- enable / disable (yes/no field type) ;
- Add text {input text field type};
- upload image;

the upload image field must have the option to delete the image too.

For enable / disable I add this in the system.xml:

  <section id="mymodule" translate="label" sortOrder="130" showInDefault="1" showInWebsite="1" showInStore="1">
        <class>separator-top</class>
        <label>Module</label>
        <tab>mymodule</tab>
        <resource>Module_First::mymodule_configuration</resource>
        <group id="general" translate="label" type="text" sortOrder="10" showInDefault="1" showInWebsite="0" showInStore="0">
            <label>General Configuration</label>
            <field id="enable" translate="label" type="select" sortOrder="1" showInDefault="1" showInWebsite="0" showInStore="0">
                <label>Enable</label>
                <source_model>Magento\Config\Model\Config\Source\Yesno</source_model>
            </field>
        </group>
    </section>

I want to know what is the format for adminhtml/system.xml and how I can check this fields value in the phtml file (or what is the best way to check the value for this fields).

Thank you

Best Answer

Add below code into each of your controller at first line of execute method:

if (!$this->moduleEnabled()) {
    return $this->_forwardNoroute();
}

moduleEnabled():

/**
 * Retrieve true if extension is enabled.
 *
 * @return bool
 */
protected function moduleEnabled()
{
    return (bool) $this->getConfigValue(
        self::XML_PATH_EXTENSION_ENABLED,
        \Magento\Store\Model\ScopeInterface::SCOPE_STORE
    );
}

XML_PATH_EXTENSION_ENABLED contains path of system.xml to enabled/disabled module

/**
 * Extension enabled config path
 */
const XML_PATH_EXTENSION_ENABLED = '<Secton_Name>/general/enabled';
Related Topic