In this post I am going to explain how to Set Default Values for System Configuration Fields in Magento 2.
First we will make one “system.xml” file at below path.
Path: app/code/<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="ht" translate="label" sortOrder="999999">
<label>HT</label>
</tab>
<section id="mymodulesection" translate="label" type="text" sortOrder="30" showInDefault="1" showInWebsite="1" showInStore="1">
<class>separator-top</class>
<label>My Module</label>
<tab>ht</tab>
<resource>Magento_Config::config_admin</resource>
<group id="general" translate="label" type="text" sortOrder="10" showInDefault="1" showInWebsite="1" showInStore="1">
<label>General</label>
<field id="enabled" translate="label" type="select" sortOrder="5" showInDefault="1" showInWebsite="1" showInStore="1">
<label>Enabled</label>
<source_model>Magento\Config\Model\Config\Source\Yesno</source_model>
</field>
<field id="welcome_text" translate="label" type="text" sortOrder="10" showInDefault="1" showInWebsite="1" showInStore="1">
<label>Welcome Text</label>
</field>
</group>
</section>
</system>
</config>
Now, we need to set default values for above system config fields.
For that add one file “config.xml” at below path.
Path: app/code/<vendor>/<module>/etc/config.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../Store/etc/config.xsd">
<default>
<mymodulesection>
<general>
<enabled>1</enabled>
<welcome_text>Welcome</welcome_text>
</general>
</mymodulesection>
</default>
</config>
The path of the field is “section/grounp/field”.
Here our section is “mymodulesection”, group is “general” and fields are “enabled” and “welcome_text”.
This code will make default system config value when you install module.
Hope this article will help you in some way, You can see useful articles in the next articles.
Anything you need support from Magento 2 feel free to contact us at Alothemes and
Phone: (+84)865633728
Email: support@alothemes.com
Leave a Reply