Categories: How ToMagento 2

How to Create Dynamic Generated Field in System Configuration of Magento 2

The system configuration is the heart of any extension from where every functionalities and feature can be handled by the store owner. It enables Magento developer to scale and meet customer’s requirements. Till date, we have written several blogs regarding adding different configuration fields in our MageComp Blog. But many times you came across the requirement of capturing multiple values irrespective of the number of values, at that time we need to use the dynamic field inside backend configuration so the admin can add multiple values using the backend.

Recently we have written a blog on “How to get Dynamic Generated row value of System Configuration in Magento 2” where you can learn how to fetch values using this dynamic field block, but after that blog some of our readers requested us to write another blog on “How to Create Dynamic Generated Field inside Magento 2 backend configuration”. Because as a developer, many times you need to fetch multiple user inputs at that time making use of Dynamic Generated Field can make your work easy. So simply follow the below steps and create your own dynamic value field in Magento 2 backend configuration.

First, we need to create “Module.xml” file inside our custom extension etc folder.
app\code\Vendor\Extension\etc\Module.xml

<pre class="lang:default decode:true">
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
        <module name="Vendor_Extension" setup_version="1.0.0">
    </module>
</config>
</pre>

After that, we need to create one more “Adminhtml.xml” in the same folder using below code.
app\code\Vendor\Extension\etc\Adminhtml.xml

<pre class="lang:default decode:true">
<?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="extension" translate="label" sortOrder="50">
            <label>Extension</label>
        </tab>
        <section id="section_extension" showInDefault="1">
            <tab>extension</tab>
            <label>Extension</label>
            <resource>Vender_Extension::config_extension</resource>
            <group id="general" translate="label" type="text" sortOrder="10" showInDefault="1" showInWebsite="1" showInStore="1">
                <label>Configuration</label>
                <field id="extension" translate="label" sortOrder="10" showInDefault="1" showInWebsite="1" showInStore="1">
                    <label>Extensions</label>
                    <backend_model>Vender\Extension\Block\Adminhtml\Config\Backend\Fileextension</backend_model>
                    <frontend_model>Vender\Extension\Block\Adminhtml\Fileextension</frontend_model>
                </field>
            </group>
        </section>
    </system>
</config>
</pre>

Now we need to create one more file “Fileextension.php” at this path.
app\code\Vendor\Extension\Block\Adminhtml\Fileextension.php

<pre class="lang:default decode:true">
<?php
namespace Vender\Extension\Block\Adminhtml;
 
use Magento\Config\Block\System\Config\Form\Field\FieldArray\AbstractFieldArray;
 
class Fileextension extends AbstractFieldArray
{
 protected function _prepareToRender()
 {
        $this->addColumn(
            'Extensions',
         [
                'label' => __('Extensions'),
                'size' => '200px'
         ]
     );
        $this->_addAfter = false;
        $this->_addButtonLabel = __('Add');
 }
}
</pre>

In this last step we need to create “Fileextension.php” for creating backend configuration field.
app\code\Vendor\Extension\Block\Adminhtml\Config\Backend\Fileextension.php

<pre class="lang:default decode:true">
<?php
namespace Vender\Extension\Block\Adminhtml\Config\Backend;
 
use Magento\Framework\App\Cache\TypeListInterface;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Framework\App\Config\Value as ConfigValue;
use Magento\Framework\Data\Collection\AbstractDb;
use Magento\Framework\Model\Context;
use Magento\Framework\Model\ResourceModel\AbstractResource;
use Magento\Framework\Registry;
use Magento\Framework\Serialize\SerializerInterface;
class Fileextension extends ConfigValue
{
 protected $serializer;
 public function __construct(
        SerializerInterface $serializer,
     Context $context,
     Registry $registry,
        ScopeConfigInterface $config,
        TypeListInterface $cacheTypeList,
        AbstractResource $resource = null,
        AbstractDb $resourceCollection = null,
     array $data = []
 ) {
        $this->serializer = $serializer;
        parent::__construct($context, $registry, $config, $cacheTypeList, $resource, $resourceCollection, $data);
 }
 public function beforeSave()
 {
     $value = $this->getValue();
        unset($value['__empty']);
        $encodedValue = $this->serializer->serialize($value);
        $this->setValue($encodedValue);
 }
 protected function _afterLoad()
 {
     $value = $this->getValue();
        if($value) {
            $decodedValue = $this->serializer->unserialize($value);
            $this->setValue($decodedValue);
     }
 }
}
</pre>

Tadaa! You have successfully created a dynamic field in backend configuration now you are free to manipulate this code according to your development needs.

If you found this blog helpful, don’t forget to share it with your colleagues and Magento Friends.

And, Let us know if you are facing an issue while implementing this code.

Happy Coding!

Click to rate this post!
[Total: 12 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

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…

22 hours 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…

22 hours ago

The ABCs of Geofencing: Definition, Features and Uses

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

2 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…

3 days ago

6 Innovative Tools Revolutionizing E-Commerce Operations

E-commerce has transformed the way consumers shop for products and services and interact with businesses.…

5 days ago

How Upcoming Cookie Changes Will Affect Your E-commerce Website?

The e-commerce world is constantly in flux. New tech and strategies emerge daily to help…

5 days ago