1

I want a multi-select drop down in system configuration with dynamic field. So How to create ? Please check this image.

enter image description here

1

1 Answer 1

4

You can acheive this by implementing like Below code :

Add below code in your system.xml file.

app\code\Vendor\Extension\etc\adminhtml

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../Magento/Backend/etc/system_file.xsd">
<system>
  <tab id="extension" translate="label" sortOrder="100">
     <label>My Extension Configuration</label>
  </tab>
  <section id="extension" translate="label" type="text" sortOrder="10" showInDefault="1" showInWebsite="1" showInStore="1">
     <label>Add Dynamic Row Multiselect</label>
     <tab>extension</tab>
     <resource>Vendor_Extension::extension</resource>
     <group id="quantity_ranges" translate="label" type="text" sortOrder="10" showInDefault="1" showInWebsite="1" showInStore="1">
            <label> Add Dynamic Row Multiselect </label>
            <field id="ranges" translate="label" sortOrder="5" showInDefault="1" showInWebsite="1" showInStore="1">
                <label>Dynamic Field</label>
                <frontend_model>Vendor\Extension\Block\Adminhtml\Form\Field\Groups</frontend_model>
                <backend_model>Magento\Config\Model\Config\Backend\Serialized\ArraySerialized</backend_model>
            </field>
        </group>
  </section>
</system>

Now, we have to create one more file “Groups.php” inside the Block folder.

app\code\Vendor\Extension\Block\Adminhtml\Form\Field\Groups.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;
    
    class Groups extends AbstractFieldArray
    {
        /**
         * @var \Magento\Framework\View\Element\BlockInterface
         */
        protected $paymentMethod;
        /**
         * @var \Magento\Framework\View\Element\BlockInterface
         */
        protected $customerGpRenderer;
    
        protected function _prepareToRender()
        {
            // For Customer Groups
            $this->addColumn('customer_gp', [
                'label' => __('Customer Group'),
                'renderer' => $this->getCustomerGpRenderer(),
                'extra_params' => 'multiple="multiple"'
            ]);
    
            // For Payment Methods
            $this->addColumn('payment_method', [
                'label' => __('Payment Method'),
                'renderer' => $this->getPaymentRenderer(),
                'extra_params' => 'multiple="multiple"'
            ]);
    
            $this->_addAfter = false;
            $this->_addButtonLabel = __('Add');
        }
    
        protected function _prepareArrayRow(DataObject $row)
        {
            $options = [];
            $paymentMethods = $row->getPaymentMethod();
            $customerGps = $row->getCustomerGp();
            if (count($paymentMethods) > 0) {
                foreach ($paymentMethods as $method) {
                    $options['option_' . $this->getPaymentRenderer()->calcOptionHash($method)]
                        = 'selected="selected"';
                }
            }
    
            if (count($customerGps) > 0) {
                foreach ($customerGps as $gp) {
                    $options['option_' . $this->getCustomerGpRenderer()->calcOptionHash($gp)]
                        = 'selected="selected"';
                }
            }
            $row->setData('option_extra_attrs', $options);
        }
    
        protected function getPaymentRenderer()
        {
           
            if (!$this->paymentMethod) {
            $this->paymentMethod = $this->getLayout()->createBlock(
                \Vendor\Extension\Block\Adminhtml\Form\Field\PaymentMethodColumn::class,
                '',
                ['data' => ['is_render_to_js_template' => true]]
            );
        }
        return $this->paymentMethod;
        }
    
        protected function getCustomerGpRenderer()
        {
            if (!$this->customerGpRenderer) {
               $this->customerGpRenderer = $this->getLayout()->createBlock(
                \Vendor\Extension\Block\Adminhtml\Form\Field\CustomerGpColumn::class,
                '',
                ['data' => ['is_render_to_js_template' => true]]
            );
            }
            return $this->customerGpRenderer;
        }
    }

Now, Create “PaymentMethodColumn.php” inside the same Block folder.

app\code\Vendor\Extension\Block\Adminhtml\Form\Field\PaymentMethodColumn.php

<?php
namespace Vendor\Extension\Block\Adminhtml\Form\Field;

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

class PaymentMethodColumn extends Select
{

    /**
     * @var \Magento\Framework\App\Config\ScopeConfigInterface
     */
    private $_appConfigScopeConfigInterface;
    /**
     * @var \Magento\Payment\Model\Config
     */
    private $_paymentModelConfig;

    public function __construct(
        Context $context,
        \Magento\Payment\Model\Config $paymentModelConfig,
        \Magento\Framework\App\Config\ScopeConfigInterface $appConfigScopeConfigInterface,
        array $data = []
    ) {
        parent::__construct($context, $data);
        $this->_appConfigScopeConfigInterface = $appConfigScopeConfigInterface;
        $this->_paymentModelConfig = $paymentModelConfig;
    }

    public function setInputName($value)
    {
        return $this->setName($value . '[]');
    }

    public function _toHtml(): string
    {
        if (!$this->getOptions()) {
            $this->setOptions($this->getPaymentMethods());
        }
        $this->setExtraParams('multiple="multiple"');
        return parent::_toHtml();
    }

    public function getPaymentMethods()
    {
        $payments = $this->_paymentModelConfig->getActiveMethods();
        $methods = [];
        foreach ($payments as $paymentCode => $paymentModel) {
            $paymentTitle = $this->_appConfigScopeConfigInterface
                ->getValue('payment/'.$paymentCode.'/title');
            $methods[] = array(
                'value' => $paymentCode,
                'label' => $paymentTitle
            );
        }
        return $methods;
    }
}

Lastly Create "CustomerGpColumn.php" inside the same Block folder.

app\code\Vendor\Extension\Block\Adminhtml\Form\Field\CUstomerGpColumn.php

<?php
namespace Vendor\Extension\Block\Adminhtml\Form\Field;

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

class CustomerGpColumn extends Select
{

    /**
     * @var \Magento\Customer\Model\ResourceModel\Group\Collection
     */
    private $customerGp;

    public function __construct(
        Context $context,
        \Magento\Customer\Model\ResourceModel\Group\Collection $customerGp,
        array $data = []
    ) {
        parent::__construct($context, $data);
        $this->customerGp = $customerGp;
    }

    public function setInputName($value)
    {
        return $this->setName($value . '[]');
    }

    public function _toHtml(): string
    {
        if (!$this->getOptions()) {
            $this->setOptions($this->getCustomerGps());
        }
        $this->setExtraParams('multiple="multiple"');
        return parent::_toHtml();
    }

    public function getCustomerGps()
    {
        $gps = $this->customerGp->toOptionArray();
        return $gps;
    }
}

After That Run the following commands :

-> rm -rf generated/* var/cache/*
-> php bin/magento setup:di:compile
-> php bin/magento cache:flush

Results : enter image description here

7
  • @rahulraj-vdc Have you tried the above code..? Mar 17, 2022 at 11:08
  • sry but this is not working and plz get the payment method not country Mar 21, 2022 at 9:47
  • @rahulrajvdc , Defenitely it will works, If you want the payment methods, I have updated my answer check it Mar 21, 2022 at 10:54
  • hello sir how to create in shipping dynamic filed Mar 22, 2022 at 9:23
  • @rahulrajvdc, according to your question : I want a multi-select drop down in system configuration with dynamic field I have given the answer. "in shipping", Please elaborate more or edit your question and explain exactly what issue you are facing. Mar 22, 2022 at 12:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.