Magento, Magento 2

Magento 2 : How to Add Multi Select Dropdown in System Configuration

In this tutorial, Today I will explain to how to add multi select dropdown in system configuration in Magento 2. Multi select dropdown is useful when you want to save more than single value in single field. Magento 2 by default provide multi select field. But, when you want to manage large amount of data at that time that multi select field will not useful. You need to manage that by multi select dropdown.

So, Let’s start

Steps to add multi select dropdown in system configuration in Magento 2:

You may also like this :

1) First of all, Let’s assume that you have created simple module. Add this below code in your system.xml file to add multi select dropdown to system configuration at this file path app/code/RH/MultiSelectCategory/etc/adminhtml/ :


<!--
/**
 * Created By : Rohan Hapani
 */
-->
<field id="category_multiselect" translate="label" type="multiselect" showInDefault="1" showInWebsite="1" showInStore="1" sortOrder="10">
    <label>Category Multi Select Dropdown</label>
    <source_model>RH\MultiSelectCategory\Model\Source\Category</source_model>
    <frontend_model>RH\MultiSelectCategory\Block\Adminhtml\MultiSelect</frontend_model>
    <can_be_empty>1</can_be_empty>
</field>

2) Secondly, Create Block file MultiSelect.php at this file path  app/code/RH/MultiSelectCategory/Block/Adminhtml/ and paste the below code:


<?php
/**
 * Created By : Rohan Hapani
 */
namespace RH\MultiSelectCategory\Block\Adminhtml;

class MultiSelect extends \Magento\Config\Block\System\Config\Form\Field
{

    /**
     * Retrieve Element HTML fragment
     *
     * @param AbstractElement $element
     * @return string
     */
    protected function _getElementHtml(\Magento\Framework\Data\Form\Element\AbstractElement $element)
    {
        $script = " <script>
                require([
                    'jquery',
                    'chosen'
                ], function ($, chosen) {
                    $('#" . $element->getId() . "').chosen({
                        width: '100%',
                        placeholder_text: '" . __('Select Options') . "'
                    });
                    $('#" . $element->getId() . "_inherit').change(function() {

                        $('#" . $element->getId() . "').prop('disabled', $(this).is(':checked'));
                          $('#" . $element->getId() . "').trigger('chosen:updated');
                    });
                })
            </script>";
        return parent::_getElementHtml($element) . $script;
    }
}

Here, I used chosen third party js to manage multi select functionality in system configuration.

3) Then, Create Category.php file and paste this below code at this file path app/code/RH/MultiSelectCategory/Model/Source/ to add category collection option in dropdown:


<?php
/**
 * Created By : Rohan Hapani
 */
namespace RH\MultiSelectCategory\Model\Source;

use Magento\Framework\Option\ArrayInterface;

class Category implements ArrayInterface
{

    protected $collectionFactory;

    /**
     * @param EavConfig $eavConfig
     */
    public function __construct(
        \Magento\Catalog\Model\ResourceModel\Category\CollectionFactory $collectionFactory
    ) {
        $this->collectionFactory = $collectionFactory;
    }

    public function toOptionArray()
    {
        $optionArray = [];
        $arr = $this->collectionFactory->create()->addAttributeToSelect('*');
        foreach ($arr as $key => $value) {
                $optionArray[] = [
                    'value' => $value->getId(),
                    'label' => $value->getName(),
                ];
        }
        return $optionArray;
    }
}

4) After that, Create adminhtml_system_config_edit.xml file at app/code/RH/MultiSelectCategory/view/adminhtml/layout/ and paste this below code to add chosen plugin CSS :


<?xml version="1.0" encoding="UTF-8"?>
<!--
/**
 * Created By : Rohan Hapani
 */
-->
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <head>
        <css src="RH_MultiSelectCategory::css/chosen/chosen.css"/>
    </head>
</page>

5) In Last, Create requirejs-config.js file at app/code/RH/MultiSelectCategory/view/adminhtml and paste the below code to add chosen js library :


var config = {
    map: {
        '*': {
            chosen: 'RH_MultiSelectCategory/js/chosen/chosen.jquery'
        }
    }
};

You can download zip file for chose css and js from this link : Click Here

After download that add this web folder at app/code/RH/MultiSelectCategory/view/adminhtml.

That’s it !!!

Now, Just upgrade, deploy and clean cache.


php bin/magento s:up
php bin/magento s:s:d -f
php bin/magento c:c

I hope this blog is easy to understand about how to add multi select dropdown in system configuration in Magento 2. In case, I missed anything or need to add some information, always feel free to leave a comment in this blog, I’ll get back with proper solution.

Stay Safe and Stay Connected !!

Tagged ,