How To

How to Add Dynamic System Configuration Field in Magento  2

Hello Magento Pals 👋,

Today I am going to demonstrate How to Add Dynamic System Configuration in Magento 2. Look at the previous topic, if you missed out, Magento 2: Add Swatch Data in Layered Navigation Aggregations in GraphQL.

System Configuration is a very useful aspect for Magento. Many times, Magento developers come across the requirement to add dynamic fields to system configuration to meet the store needs. Dynamic fields are used to manage complex data via system configurations. The admin can add, modify, and even delete the dynamic fields as per the necessity through system configuration.

So, let’s explore the steps to Add Dynamic System Configuration field in Magento 2 🚀

How to Add Dynamic System Configuration Field in Magento  2:

Step 1: Create one sample System.xml in the following path:

app/code/Vendor/Extension/etc/adminhtml/system.xml

Then, add the below code:

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="../../../../Magento/Backend/etc/system_file.xsd">
    <system>
        <tab id="vendortab" translate="label" sortOrder="100">
            <label>Vendor TAB</label>
        </tab>
        <section id="sectionid" translate="label" sortOrder="20" showInDefault="1" showInWebsite="1" showInStore="1">
            <class>separator-top</class>
            <label>General Config</label>
            <tab>vendortab</tab>
            <resource>Vendor_Extension::config</resource>
            <group id="group" translate="label" type="text" sortOrder="10" showInDefault="1" showInWebsite="0" showInStore="0">
                <label>General Configuration</label>
                    <field id="field" translate="label" type="text" sortOrder="10" showInDefault="1" showInWebsite="1"
                       showInStore="1">
                    <label>Field</label>
                </field>
            </group>
        </section>
    </system>
</config>

Step 2: To do this, create di.xml in the following path:

app\code\Vendor\Extension\etc\adminhtml\di.xml

Now, add the below code:

<?xml version="1.0" ?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <type name="Magento\Config\Model\Config\Structure\Data">
        <plugin name="vendor_dynamic" type="Vendor\Extension\Plugin\Config\Field\Data"/>
    </type>
</config>                                        

Step 3: Next, create a Plugin with name Data.php file in Plugin:

 app\code\Vendor\Extension\Plugin\Config\Field\Data.php

and add this code to the file:

<?php
namespace Vendor\Extension\Plugin\Config\Field;

use Magento\Config\Model\Config\Structure\Data as StructureData;
use Magento\Framework\Module\ModuleListInterface;
class Data
{
    public function __construct(ModuleListInterface $moduleList)
    {
        $this->_moduleList = $moduleList;
    }
    public function beforeMerge(StructureData $object, array $config)
    {
       $moduleList = $this->_moduleList->getNames();
       foreach ($moduleList as $name)
       {
          if (strpos($name, 'Vendor_Extension') === false)
          {
               continue;
           }
           $this->moduleslist[] = $name;
        }
        if (!isset($config['config']['system']))
        {
            return [$config];
        }

        $sections = $config['config']['system']['sections'];
        foreach ($sections as $sectionId => $section)
        {
            if (isset($section['tab']) && ($section['tab'] === 'vendor') && ($section['id'] !== 'vendor'))
            {
                foreach ($this->moduleslist as $moduleName)
                {
                    if ($section['id'] !== 'sectionid')
                    {
                        continue;
                    }
                    $dynamicGroups = $this->getGroups($moduleName, $section['id']);
                    if (!empty($dynamicGroups))
                    {
                        $config['config']['system']['sections'][$sectionId]['children'] = $dynamicGroups + $section['children'];
                    }
                    break;
                }
            }
        }

        return [$config];
    }
    protected function getGroups($moduleName, $sectionName)
    {
        $defaultFieldOptions = [
            'type'          => 'text',
            'showInDefault' => '1',
            'showInWebsite' => '1',
            'showInStore'   => '1',
            'sortOrder'     => 1,
            'module_name'   => $moduleName,
            'validate'      => 'required-entry',
            '_elementType'  => 'field',
            'path'          => $sectionName . '/module'
        ];

        $fields = [];
        foreach ($this->getNewField() as $id => $option)
        {
            $fields[$id] = array_merge($defaultFieldOptions, ['id' => $id], $option);
        }

        return [
            'module' => [
                'id'            => 'module',
                'label'         => __('Dynamic Section'),
                'showInDefault' => '1',
                'showInWebsite' => '0',
                'showInStore'   => '0',
                '_elementType'  => 'group',
                'path'          => $sectionName,
                'children'      => $fields
            ]
        ];
    }
    protected function getNewField()
    {
        return [
            'name1'        => [
                'label'          => __('Dynamic Field'),
                'frontend_class' => 'vendor_dynamic_class',
                'show'           => 1,
                'tooltip'  => __('Dynamic Field Tooltip'),
                'comment'  => __('Dynamic Field Comment')
            ],
        ];
    }
}

It’s done!

You can check the output from the admin panel. It looks like below… 

Output:

Concluding Words:

This way you can Add Dynamic System Configuration Field in Magento 2. Add your questions in the comment section and I will be glad to be of help. 

Relevantly, you may also like to read – 

Keep in touch, Keep rating and Keep sharing!

Happy Coding 😊

Click to rate this post!
[Total: 1 Average: 5]
Dhiren Vasoya

Dhiren Vasoya is a Director and Co-founder at MageComp, Passionate 🎖️ Certified Magento Developer👨‍💻. He has more than 9 years of experience in Magento Development and completed 850+ projects to solve the most important E-commerce challenges. He is fond❤️ of coding and if he is not busy developing then you can find him at the cricket ground, hitting boundaries.🏏

Recent Posts

Magento 2: Add Quantity Increment and Decrement on Category Page

Hello Magento Friends, In this blog, we will discuss about adding quantity increment and decrement…

15 hours ago

How to Integrate ChatGPT with Laravel Application?

In this guide, we'll explore how to integrate ChatGPT, an AI-powered chatbot, with a Laravel…

4 days ago

What are Net Sales? How to Calculate Your Net Sales?

In the world of business, understanding financial metrics is crucial for making informed decisions and…

6 days ago

Magento 2 Extensions Digest April 2024 (New Release & Updates)

Welcome to the MageComp Monthly Digest, where we bring you the latest updates, releases, and…

6 days ago

The ABCs of Geofencing: Definition, Features and Uses

In this era, businesses are always on the lookout for ways to engage with their…

7 days ago

How to Delete Product Variant in a Shopify Remix App using GraphQL Mutations?

Managing a Shopify store efficiently involves keeping your product catalog organized. This includes removing outdated…

1 week ago