How to Add Dynamic Row Multi Select Option in system.xml Configuration in Magento 2

Hello Everyone,

In this blog, we will learn about how to Add Dynamic Row Option in system.xml in Magento 2.

In our previous blog we already learned how to create system.xml configuration files and various select option types.

Without wasting your time, let us guide you straight away. Follow the easy step given below to Add Dynamic Row Multi Select Option in Configuration File in Magento 2.

STEPS FOR ADD DYNAMIC ROW OPTION IN MAGENTO 2

Step 1: Create system.xml file

app/code/Vendor/Extension/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="magecurious" class="magecurious" translate="label" sortOrder="10">

            <label>Magecurious</label>

        </tab>

        <section id="extension" translate="label" sortOrder="10" showInDefault="1" showInWebsite="1" showInStore="1">

            <class>separator-top</class>

            <label>Magecurious</label>

            <tab>magecurious</tab>

            <resource>Vendor_Extension::config_extension</resource>

            <group id="general" translate="label" type="text" sortOrder="1" showInDefault="1" showInWebsite="1" showInStore="1">

                <label>General Configuration</label>

<field id="enable" translate="label" type="select" sortOrder="1" showInDefault="1" showInWebsite="1" showInStore="1">

                    <label>Enable Extension</label>

                 <source_model>Magento\Config\Model\Config\Source\Enabledisable</source_model>

                </field>

<field id="vendor_dynamic_field" translate="label" sortOrder="10" showInDefault="1" showInWebsite="1" showInStore="1">

<label>Dynamic Row</label>

<frontend_model>Vendor\Extension\Block\Adminhtml\Form\Field\Row</frontend_model>

<backend_model>Magento\Config\Model\Config\Backend\Serialized\ArraySerialized</backend_model>

</field>

            </group>

        </section>

    </system>

</config>

Step 2: Create Column.php file

app/code/Vendor/Extension/Block/Adminhtml/Form/Field/Column.php

<?php

namespace Vendor\Extension\Block\Adminhtml\Form\Field;

use Magento\Framework\View\Element\Html\Select;

class Column extends Select

{

    /**

     * SetInputName function

     *

     * @param [type] $value

     * @return void

     */

    public function setInputName($value)

    {

        return $this->setName($value);

    }

    /**

     * SetInputId function

     *

     * @param [type] $value

     * @return void

     */

    public function setInputId($value)

    {

        return $this->setId($value);

    }

    /**

     * Render block HTML

     *

     * @return string

     */

    public function _toHtml()

    {

        if (!$this->getOptions()) {

            $this->setOptions($this->getSourceOptions());

        }

        return parent::_toHtml();

    }

    /**

     * GetSourceOptions function

     *

     * @return array

     */

    private function getSourceOptions()

    {

        return [

            ['label' => 'Yes', 'value' => '1'],

            ['label' => 'No', 'value' => '0'],

        ];

    }

}

Step 3: Create Row.php file

app/code/Vendor/Extension/Block/Adminhtml/Form/Field/Row.php

<?php

namespace Vendor\Extension\Block\Adminhtml\Form\Field;

use Magento\Config\Block\System\Config\Form\Field\FieldArray\AbstractFieldArray;

use Magento\Framework\DataObject;

use Magento\Framework\Exception\LocalizedException;

use Vendor\Extension\Block\Adminhtml\Form\Field\Column;

class Row extends AbstractFieldArray

{

    /**

     * @var Templete

     */

    private $templeteRenderer;

    /**

     * Prepare rendering the new field by adding all the needed columns

     */

    protected function _prepareToRender()

    {

        $this->addColumn('text_1', ['label' => __('Text 1'), 'class' => 'required-entry']);

        $this->addColumn('text_2', ['label' => __('Text 2'), 'class' => 'required-entry']);

        $this->addColumn('templete', [

            'label' => __('Select'),

            'renderer' => $this->getTempleteRenderer()

        ]);

        $this->_addAfter = false;

        $this->_addButtonLabel = __('Add Row');

    }

    /**

     * Prepare existing row data object

     *

     * @param DataObject $row

     * @throws LocalizedException

     */

    protected function _prepareArrayRow(DataObject $row): void

    {

        $options = [];

        $templete = $row->getTemplete();

        if ($templete !== null) {

            $options['option_' . $this->getTempleteRenderer()->calcOptionHash($templete)] = 'selected="selected"';

        }

        $row->setData('option_extra_attrs', $options);

    }

    /**

     *

     * @return Templete

     * @throws LocalizedException

     */

    private function getTempleteRenderer()

    {

        if (!$this->templeteRenderer) {

            $this->templeteRenderer = $this->getLayout()->createBlock(

                Column::class,

                '',

                ['data' => ['is_render_to_js_template' => true]]

            );

        }

        return $this->templeteRenderer;

    }

}

Step 4: Finally run the below commands

$ php bin/magento cache:clean

$ php bin/magento cache:flush

Step 5: Output:

Final Thoughts:

So this was the easiest way which we have told you in this blog. This is how you can Add Dynamic Row Multi Select Option in the system.xml configuration file in Magento 2. Hope you liked the blog.

So quickly go to the comment box and tell me how you like this blog?

Stay tuned with us on our site to get new updates of Magento.

Thanks for reading and visiting our site.

How useful was this post?

Click on a star to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this post.

Leave a Reply

Your email address will not be published. Required fields are marked *