Read More
Read More
Menu Close

    How to Add Dynamic Rows in Magento 2 Configuration.

    In this article, We will learn about How to Add Dynamic Rows in Magento 2 Configuration using the system.xml file. Dynamic rows are very helpful at the time of saving the dynamic values.

    In Magento 2, We can set various UI component fields such as textbox, dropdown, multi-select, and many more.

    1). First, We have to create the module registration file named registration.php in app\code\Webkul\Dynamicrow

    \Magento\Framework\Component\ComponentRegistrar::register(
        \Magento\Framework\Component\ComponentRegistrar::MODULE,
        'Webkul_Dynamicrow',
        __DIR__
    );

    2). Now, We have to Create module.xml file at app\code\Webkul\Dynamicrow\etc

    <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
        <module name="Webkul_Dynamicrow"></module>
    </config>

    3). Thereafter, We have to Create system.xml file at app\code\Webkul\Dynamicrow\etc\adminhtml

    <?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="webkul" sortOrder="10">
                <label>Webkul</label>
            </tab>
           <section id="dynamicrow" translate="label" type="text" sortOrder="310" showInDefault="1" showInWebsite="0" showInStore="0">
                <label>Dynamicrow</label>
                <tab>webkul</tab>
                <resource>Webkul_Dynamicrow::configuration</resource>
                <group id="general" translate="label" type="text" sortOrder="10" showInDefault="1" showInWebsite="1"
                       showInStore="1">
                    <label>Add Dynamic Row</label> 
                    <field id="dynamic_field" translate="label" sortOrder="10" showInDefault="1" showInWebsite="1"
                           showInStore="1">
                        <label>Dynamic Row</label>
                        <frontend_model>Webkul\Dynamicrow\Block\Adminhtml\Form\Field\Row</frontend_model>
                        <backend_model>Magento\Config\Model\Config\Backend\Serialized\ArraySerialized</backend_model>
                    </field>
                </group>
            </section>
        </system>
    </config>

    4). After that, Create DynamicColumn.php file at app\code\Webkul\Dynamicrow\Block\Adminhtml\Form\Field

    <?php
      
    namespace Webkul\Dynamicrow\Block\Adminhtml\Form\Field;
    
    use Magento\Framework\View\Element\Html\Select;
    
    class DynamicColumn 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'],
            ];
        }
    }

    5). Lastly, Create Row.php file at app\code\Webkul\Dynamicrow\Block\Form\Field

    <?php
    
    namespace Webkul\Dynamicrow\Block\Adminhtml\Form\Field;
    
    use Magento\Config\Block\System\Config\Form\Field\FieldArray\AbstractFieldArray;
    use Magento\Framework\DataObject;
    use Magento\Framework\Exception\LocalizedException;
    use Webkul\Dynamicrow\Block\Adminhtml\Form\Field\DynamicColumn;
    
    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(
                    DynamicColumn::class,
                    '',
                    ['data' => ['is_render_to_js_template' => true]]
                );
            }
            return $this->templeteRenderer;
        }
    }
    row

    Start your headless eCommerce
    now.
    Read More
    . . .
    Discuss on Helpdesk

    Leave a Comment

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


    Be the first to comment.

    Back to Top