John John - 5 months ago 18
PHP Question

Magento 2: system.xml in custom module

Is it possible to add a

system.xml
file for module configurations in Magento 2? If so, how?

Answer

Yes, In magento 2 it's possible to create system configuration file same as Magento 1.x. But it will need to create some other files.

Need to use following file to create it.

1) app/code/Vendor/Helloworld/etc/adminhtml/system.xml

2) app/code/Vendor/Helloworld/etc/acl.xml

This 2 files are important to create system configuration.

In system.xml file

Adding the common content

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../Config/etc/system_file.xsd">
    <system>
        <!-- Add new Tab -->
        <tab id="vendor" translate="label" sortOrder="300">
            <label>Vendor Extension</label>
        </tab>
        <section id="helloworld" translate="label" type="text" sortOrder="140" showInDefault="1" showInWebsite="1" showInStore="1">
            <label>Helloworld</label>
            <tab>vendor</tab>
            <!-- resource tag name which we have to defined in the acl.xml -->
            <resource>Vendor_Helloworld::config_helloworld</resource>
        </section>
        <group id="general" translate="label" type="text" sortOrder="1" showInDefault="1" showInWebsite="1" showInStore="1">
            <label>General Options</label>
            <field id="active" translate="label" type="select" sortOrder="1" showInDefault="1" showInWebsite="1" showInStore="1">
                <label>Enabled</label>
                <source_model>Magento\Config\Model\Config\Source\Yesno</source_model>
            </field>
        </group>
    </system>
</config>

In acl.xml file

In the file need to write the below content

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../lib/internal/Magento/Framework/Acl/etc/acl.xsd">
    <acl>
        <resources>
            <resource id="Magento_Backend::admin">
                <resource id="Magento_Backend::stores">
                    <resource id="Magento_Backend::stores_settings">
                        <resource id="Magento_Config::config">
                            <!-- this resource id we can use in system.xml for section -->
                            <resource id="Vendor_Helloworld::config_helloworld" title="Helloworld Section" sortOrder="80" />
                        </resource>
                    </resource>
                </resource>
            </resource>
        </resources>
    </acl>
</config>

After that, Clear the magento cache & logout from admin side. Then Login at admin side. In store > Configuration you can see the tab “Vendor Extension”. When you click on this you can see the detail of this.

Comments