How to setup configuration setting for a module in Magento 2?

By: Amit Tiwari, Oct 19th, 2018 # How to # Magento 2

How to setup Configuration setting for a module in Magento 2
Magento 2 provides configuration system in its backend where we can create our own configuration setting as per the module requirement. We can go to Store->Setting->Configuration and check all the stored Magento configuration there. We can also add our own configuration menu and use them. Table: core_config_data All records of configuration are stored in table mentioned above. By default, there is no entry in the table when we create any configuration field. However, when we save the configuration there will be an entry in this table with its respective value so that we can trace the actual configuration value from this table.
  • Step 1: Create system.xml file.
  • Step 2: Set default configuration value.
  • Step 3: Flush Magento cache.
  • Step 4: Use configurations.
Note: Replace Aureatelabs/LoginAsCustomer from entries in this article to your module name.   Setup configuration setting for a module in Magento2

Step 1: Create system.xml file.

Create a file at the path given below and add the following code: app/code/VendorName/ThemeDirectoryName/etc/adminhtml/system.xml
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Config:etc/system_file.xsd">
   <system>
       <tab id="aureate_tab" translate="label" sortOrder="1">
           <label>Aureate Labs</label>
       </tab>
       <section id="aureatelabs" translate="label" type="text" sortOrder="100" showInDefault="1"
                showInWebsite="1" showInStore="1">
           <label>Login As Customer</label>
           <tab>aureate_tab</tab>
           <resource>Aureatelabs_LoginAsCustomer::config</resource>
           <group id="general" translate="label" type="text" sortOrder="10" showInDefault="1" showInWebsite="1"
                  showInStore="1">
               <label>General</label>
               <field id="login_as_customer_enabled" translate="label" type="select" showInDefault="1" canRestore="1"
                      showInWebsite="1" showInStore="1">
                   <label>Enabled</label>
                   <source_model>Magento\Config\Model\Config\Source\Yesno</source_model>
               </field>
           </group>
           <group id="button_visibility" translate="label" type="text" sortOrder="10" showInDefault="1"
                  showInWebsite="1" showInStore="1">
               <label>Button visibility</label>
               <field id="customer_grid_page" translate="label" type="select" showInDefault="1" canRestore="1"
                      showInWebsite="1" showInStore="1">
                   <label>Customer grid page</label>
                   <source_model>Magento\Config\Model\Config\Source\Yesno</source_model>
               </field>
           </group>
       </section>
   </system>
</config>
An overview of the code that you just saw:   In the above code, we have two groups General and Button visibility Below is the brief description of some of the tags we have used: <system>: This tag is the starting tag to indicate that we are going to system settings. Tab elements: This tag is used to create our custom menu in configuration options.
  • id: unique tab id
  • label: tab title
Section Attributes:
  • id: unique section id
  • sortOrder: set the position of our configuration menu in the list.
  • showInDefaultconfiguration scope
  • showInWebsite: configuration scope
  • showInStore: configuration scope
Section elements:
  • Label: configuration menu title (In the example it’s Aureate Labs)
  • Tab: tab_id to display this configuration
  • Resource: ACL rule to access this configuration (In the example it’s Aureatelabs_LoginAsCustomer::config) 
  • Group: group of some configurations (In the example we created two groups general and  Button visibility)
  • Fields: configuration field to store dropdown or text or radio button. The field also has some attributes and elements.  
Fields Elements:
  • Label: field title (In Example for general we have Enabled text)
  • Source_model: store data of this field, we can use it for select, multi-select type (In the example we have used Magento\Config\Model\Config\Source\Yesno For Yes/No Dropdown)
  • We can use our own source_model for options in this example we are using yesno model provided by Magento. If you want to add our own you can add.

Step 2: Set default configuration value.

Each field in system.xml after its creation will not have any value. When we call them it will return Null value because at the time of field creation there is no entry in the core_config_data table. When we click on save config button then there is an entry as per the default value of the field. If we have Yes/No field then it will show default No value (We will see how we can change it in the steps given below) but there is no entry in database level until we click on the save config button. To set our default value for the field let's consider in our example we have enabled the field for values Yes/No. After the first step when we visit the admin configuration section then we have the default value set in the field as “No”.  Now we can change it as shown below: Create a config.xml file at the path given below and add the following code: app/code/VendorName/ThemeDirectoryName/etc/config.xml Syntax:
<default>
<section>
   <group>
       <field>{value}</field>
   </group>
</section>
</default>
For Our Example
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Store:etc/config.xsd">
   <default>
       <aureatelabs>
           <general>
               <login_as_customer_enabled>1</login_as_customer_enabled>
           </general>
           <button_visibility>
               <customer_grid_page>1</customer_grid_page>
               <customer_edit_page>1</customer_edit_page>
           </button_visibility>
       </aureatelabs>
   </default>
</config>
  • <default>: default field value
  • <aureatelabs>: section id
  • <general>: group id
  • <login_as_customer_enabled>: field id which sets a default value for the field
For our example we have considered the field and its value as shown below:
  • <section>: <aureatelabs>
  • <group>: <general>
  • <field>: <login_as_customer_enabled> set this value 1 to show yes by default.

Step 3: Flush Magento cache.

Now we need to clear the cache of Magento. Using the commands given below we can clear and flush our Magento cache
  • For Clear cache : php bin\magento cache:clear OR php bin\magento c:c
  • For Flush cache : php bin\magento cache:flush OR php bin\magento c:f
Or we can also clear and flush the cache from the admin panel: System->tools->cache management

Step 4: Get value from configuration.

There are two ways to get value of configuration 1) By simply calling it:
$this->scopeConfig->getValue(aureatelabs/general/login_as_customer_enabled
,\Magento\Store\Model\ScopeInterface::SCOPE_STORE);
Above code will return value of configuration value stored in table for that field Where:   Aureatelabs: Section id General: Group id Login_as_customer_enabled: Field id 2) Using the Helper Class (Recommended): Create a file at the path given below and add the following code: app/code/Vendor/module/Helper/Data.php
namespace Aureatelabs\LoginAsCustomer\Helper;
use Magento\Framework\App\Helper\AbstractHelper;
use Magento\Store\Model\ScopeInterface;
class Data extends AbstractHelper
{
  const XML_PATH_FIELD = aureatelabs/general/';
   public function getConfigValue($field, $storeId = null)
   {
       return $this->scopeConfig->getValue(
           $field, ScopeInterface::SCOPE_STORE, $storeId
       );
   }
   public function getFieldConfig($code, $storeId = null)
   {
       return $this->getConfigValue(self::XML_PATH_FIELD.$code, $storeId);
   }
}
Now, we try to get it in the controller: Create a file at the path given below and add the following code: app/code/Aureatelabs/LoginAsCustomer/Controller/Login/index.php
namespace Aureatelabs\LoginAsCustomer\Controller\Login;
class Index extends \Magento\Framework\App\Action\Action
{
   protected $helperData;
   public function __construct(
       \Magento\Framework\App\Action\Context $context,
	\Aureatelabs\LoginAsCustomer\Helper\Data $helperData
   )
   {
       $this->helperData = $helperData;
       return parent::__construct($context);
   }
   public function execute()
   {
       // TODO: Implement execute() method.
       $CheckEnable=$this->helperData->getFieldConfig('enable');
      // You can check value of result by printing $CheckEnable value
   }
}
Hope this was helpful. If you have any queries regarding the same feel free to write to us in the comments section given below!