Back to Top

Create Dropdown in custom form using select2 js in Magento 2

Updated 25 July 2024

In this blog, we are going to learn how we can create a dropdown or select input type field in a form with dynamic options with the search features.

In Magento2, we manage a large number of products and customers, and other data.
So, if we are creating a form and we have the need to add a dropdown or select input type, then using select2 js and adding options dynamically will improve our form’s loading performance.

Please follow the below steps to add dropdown using select2 js:

1. Download the select2 js file.

2. Create routename_controller_actionname.xml file inside Vendor/CustomModule/view/frontend/layout/ directory.

<?xml version="1.0"?>
<!--
/**
 * Vendor CustomModule
 *
 * @category Webkul
 * @package  Vendor_CustomModule
 * @author   Khushboo Sahu
 */
-->
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="1column" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <head>
        <css src="Vendor_CustomModule::css/select2.css" rel="stylesheet" type="text/css" />
    </head>
    <body>
        <referenceContainer name="content">
            <block class="Magento\Framework\View\Element\Template" 
                name="select_demo_index" 
                template="Vendor_CustomModule::demo.phtml" 
                cacheable= "false"/>
        </referenceContainer>
    </body>
</page>

3. Create demo.phtml file inside app/code/Vendor/CustomModule/view/frontend/templates/ directory.

<?php 
$requestUrl = $block->getUrl('routename/controller/actionanme'); //to fetch customer account list
?>
<select class="select2" id="wk-customers" style="width:40%">
    <option value="">Select Customer...</option>
</select>
<br/><br/>
<button id="getvaluebtn" title="Save" type="button" class="action-default scalable action-save action-secondary">
    <span>Get Selected Option Value</span>
</button>
            
<script type="text/javascript">
    require([
        "jquery",
        "Vendor_CustomModule/js/select2"
    ], function($)  {
        $('#wk-customers').select2({
            ajax: {
                url: "<?= /* @noEscape */ $requestUrl ?>"+"?isAjax=true",
                delay: 250,
                type: "GET",
                data: function (params) {
                    return {
                        q: params.term,
                        page: params.page
                    };
                },
                error: function (response) {
                    $(".messages").css("display", "none");
                },
                processResults: function (data, params) {
                    params.page = params.page || 1;

                    return {
                        results: data.results,
                        pagination: {
                            more: (params.page * 1) < data.noOfPages
                        }
                    };
                },
                cache: true
            },
            placeholder: 'Choose Customer...',
            theme: "classic",
            templateSelection: formatListSelection
        });

        function formatListSelection (item) {
            return item.text;
        }

        $("body").on("click", "#getvaluebtn", function () {
            var newVal  = $("#wk-customers").val();
            alert(newVal);
        });
    });
</script>

4. Create style2.css file inside app/code/Vendor/CustomModule/view/frontend/web/css/ directory. And Put style2.js file inside app/code/Vendor/CustomModule/view/frontend/web/js/ directory.

5. Create Index.php file inside app/code/Vendor/CustomModule/Controller/Index/ directory.

Searching for an experienced
Magento 2 Company ?
Find out More
<?php
/**
 * Webkul Software.
 *
 * @category  Webkul
 * @package   Vendor_CustomModule
 * @author    Webkul
 * @copyright Copyright (c) Webkul Software Private Limited (https://webkul.com)
 * @license   https://store.webkul.com/license.html
 */
namespace Vendor\CustomModule\Controller\Index;

use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;
use Magento\Framework\View\Result\PageFactory;

class Index extends Action
{
    /**
     * @var PageFactory
     */
    protected $_resultPageFactory;

    /**
     * initialization
     *
     * @param Context $context
     * @param PageFactory $resultPageFactory
     */
    public function __construct(
        Context $context,
        PageFactory $resultPageFactory
    ) {
        $this->_resultPageFactory = $resultPageFactory;
        parent::__construct($context);
    }
    
    public function execute()
    {
        $resultPage = $this->_resultPageFactory->create();
        $resultPage->getConfig()->getTitle()->set(__("Select2 Demo"));
        
        return $resultPage;
    }
}

6. Now, Create CustomerAccountList.php Controller inside app/code/Vendor/CustomModule/Controller/Index/ directory.
When we will execute this controller, it will return response data in JSON format, in which the “results” key contains the customers’ list.

<?php
/**
* Webkul Software.
*
* @category  Webkul
* @package   Vendor_CustomModule
* @author    Webkul
* @copyright Webkul Software Private Limited (https://webkul.com)
* @license   https://store.webkul.com/license.html
*/

namespace Vendor\CustomModule\Controller\Index;

use Magento\Framework\Controller\ResultFactory;
use Magento\Framework\App\Action\Context;

class CustomerAccountList extends \Magento\Framework\App\Action\Action
{
    /**
     * @var ResultFactory
     */
    protected $_resultFactory;

    /**
     * @var array
     */
    protected $results = [];

    /**
     * @var int
     */
    private $resultsCount;

    /**
     * Object initialization.
     *
     * @param Context $context
     * @param \Magento\Customer\Model\CustomerFactory $customerFactory
     * @param \Magento\Framework\Controller\ResultFactory $resultFactory
     */
    public function __construct(
        Context $context,
        \Magento\Customer\Model\CustomerFactory $customerFactory,
        \Magento\Framework\Controller\ResultFactory $resultFactory
    ) {
        $this->_resultFactory  = $resultFactory;
        $this->customerFactory = $customerFactory;
        parent::__construct($context);
    }

    /**
     * Executes request and return json data
     * @return json
     */
    public function execute()
    {
        $returnArray            = [];
        $returnArray["success"] = false;
        $returnArray["message"] = "";
        $resultJson             = $this->_resultFactory->create(ResultFactory::TYPE_JSON);
        $wholeData              = $this->getRequest()->getParams();

        if ($wholeData) {
            try {
                $query       = "";
                $pageSize    = 10;
                $pageNumber  = $wholeData["page"] ?? 1;
                $query       = trim($wholeData["q"] ?? "");
                    
                $customerList = [];
                $customerList = $this->getCustomers($query, $pageSize, $pageNumber);
                        
                $returnArray["success"]    = true;
                $returnArray["results"]    = $customerList;
                $returnArray["totalCount"] = $this->resultsCount;
                $noOfPages = ($this->resultsCount > 0)?$this->resultsCount/$pageSize : 1;
                $returnArray["noOfPages"]  = ceil($noOfPages);
                    
                $resultJson->setData($returnArray);
                return $resultJson;
            } catch (\Exception $e) {
                $returnArray["message"] = $e->getMessage();
                $resultJson->setData($returnArray);
                return $resultJson;
            }
        } else {
            $returnArray["message"] = __("Invalid Request");
            $resultJson->setData($returnArray);
            return $resultJson;
        }
    }

    /**
     * get customers
     * @param string $query
     * @param int $pageSize
     * @param int $pageNumber
     * @return array
     */
    public function getCustomers($query = "", $pageSize = 20, $pageNumber = 1)
    {
        try {
            $customers = $this->customerFactory->create()
                ->getCollection()
                ->addAttributeToSelect('*');
                
            if (!empty($query)) {
                $customers->addAttributeToFilter(
                    [
                        ["attribute"=>"firstname", "like"=>'%'.$query.'%'],
                        ["attribute"=>"email",  "like"=>'%'.$query.'%'],
                        ["attribute"=>"lastname",  "like"=>'%'.$query.'%']
                    ]
                );
            }
            $this->resultsCount = $customers->count();
            if ($customers) {
                $customers->setPageSize($pageSize)->setCurPage($pageNumber);
            }
            $customers->getSelect()
                ->reset(\Zend_Db_Select::COLUMNS)
                ->columns(['entity_id', 'email', 'firstname', 'lastname']);
            $customers->getSelect()->reset(\Zend_Db_Select::ORDER);
            $customers->getSelect()->order("email", "DESC");
            
            $data = (!empty($customers)) ? $customers->getData() : [];

            if (!empty($data)) {
                foreach ($data as $index => $value) {
                    $result          = [];
                    $fullname = ($value["firstname"] ?? "")." ".($value["lastname"] ?? "");
                    $result["id"]    = $value["email"] ?? "";
                    $result["text"]  = $fullname.' ('. $result["id"] .')';
                    $this->results[] = $result;
                }
            }
        } catch (\Exception $e) {
            echo $e->getMessage();
            die("Exception Occurred");
        }
        
        return $this->results;
    }
}

7. Now, when we will execute the code and run the controller on the browser. We will get the response as in the following images.

Select2-js
Select2Search
Select2GetValue

8. Get the complete code.

Hope this will be helpful. Thanks 🙂

. . .

Leave a Comment

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


Be the first to comment.

Back to Top

Message Sent!

If you have more details or questions, you can reply to the received confirmation email.

Back to Home