Reading list Switch to dark mode

    How to use Magento 2 admin Multiselect js on frontend

    Updated 6 March 2024

    Magento-Code-Snippet-5-2

    Today we will learn how to use multiselect js used in magento2 admin on the front end. So I am assuming that you have a basic understanding of how to create a module in Magento2 if not, please read our other articles related to module development.
    First, we assume that our module name is Webkul_MultiSelect

    Now we will create the controller class in app/code/Webkul/MultiSelect/Controller/Multiselect/Demo.php:

    <?php
    /**
     * Webkul Software.
     *
     * @category  Webkul
     * @package   Webkul_MultiSelect
     * @author    Webkul
     */
    namespace Webkul\MultiSelect\Controller\Multiselect;
    
    use Magento\Framework\App\Action\Action;
    use Magento\Framework\App\Action\Context;
    use Magento\Framework\View\Result\PageFactory;
    use Magento\Customer\Model\Session;
    use Magento\Framework\App\RequestInterface;
    
    class Demo extends Action
    {
        /**
         * @var PageFactory
         */
        protected $_resultPageFactory;
        /**
         * @var Magento\Customer\Model\Session
         */
        protected $_customerSession;
    
        /**
         * @param Context                         $context
         * @param PageFactory                     $resultPageFactory
         * @param \Magento\Customer\Model\Session $customerSession   customer session
         */
        public function __construct(
            Context $context,
            PageFactory $resultPageFactory,
            Session $customerSession
        ) 
        {
            $this->_customerSession = $customerSession;
            $this->_resultPageFactory = $resultPageFactory;
            parent::__construct($context);
        }
    
        /**
         * Retrieve customer session object.
         *
         * @return \Magento\Customer\Model\Session
         */
        protected function _getSession()
        {
            return $this->_customerSession;
        }
    
        /**
         * Check customer authentication.
         *
         * @param RequestInterface $request
         *
         * @return \Magento\Framework\App\ResponseInterface
         */
        public function dispatch(RequestInterface $request)
        {
            $loginUrl = $this->_objectManager->get('Magento\Customer\Model\Url')->getLoginUrl();
    
            if (!$this->_customerSession->authenticate($loginUrl)) {
                $this->_actionFlag->set('', self::FLAG_NO_DISPATCH, true);
            }
    
            return parent::dispatch($request);
        }
    
        /**
         * multiselect demo page
         * @return \Magento\Framework\View\Result\Page
         */
        public function execute()
        {
            $pageLabel = 'Multi-Select Demo';
            $resultPage = $this->_resultPageFactory->create();
            $resultPage->getConfig()->getTitle()->set(__($pageLabel));
    
            return $resultPage;
        }
    }

    Now the block file at app/code/Webkul/MultiSelect/Block/Multiselect.php :

    <?php
    /**
     * Webkul Software multi select page block.
     *
     * @category  Webkul
     * @package   Webkul_MultiSelect
     * @author    Webkul
     */
    namespace Webkul\MultiSelect\Block;
    
    /**
     * MultiSelect block.
     *
     * @author      Webkul Software
     */
    class Multiselect extends \Magento\Framework\View\Element\Template
    {
    
        /**
         * @param \Magento\Framework\View\Element\Template\Context $context
         * @param array $data
         */
        public function __construct(
            \Magento\Framework\View\Element\Template\Context $context,
            array $data = []
        ) 
        {
            parent::__construct($context, $data);
        }
    }

    Now we will create our design files inside the view folder, first create app/code/Webkul/MultiSelect/view/frontend/layout/mselect_multiselect_demo.xml

    <?xml version="1.0"?>
    <page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
        <head>
            <css src="jquery/editableMultiselect/css/jquery.multiselect.css"/>
        </head>
        <update handle="customer_account"/>
        <body>
            <referenceContainer name="content">
                <block 
                    class="Webkul\MultiSelect\Block\Multiselect" 
                    name="multiselect_demo" 
                    template="demo.phtml"
                    cacheable="false"
                />
            </referenceContainer>
        </body>
    </page>

    Now we will create the phtml file at app/code/Webkul/MultiSelect/view/frontend/templates/demo.phtml :

    Searching for an experienced
    Magento 2 Company ?
    Find out More
    <?php 
    	/**
    	 * here we are using static values just to demostrate multi select you cna us edynamic values here
    	 */
    ?>
    <fieldset class="fieldset">
    	<legend class="legend">
    		<span><?php /* @escapeNotVerified */ echo __('Multi Select Demo') ?></span>
    	</legend>
    	<form action="#">
    		<div class="field required">
    				<label class="label">
    					<?php 
    					/* @escapeNotVerified */ echo __('Multi Select') 
    					?>:
    				</label>
    				<div class="control">
    					<select id="myElement" class="select multiselect myElement" multiple="multiple">
    						<option value="0"><?php /* @escapeNotVerified */ echo __("Value one"); ?></option>
    						<option value="2"><?php /* @escapeNotVerified */ echo __("Value two"); ?></option>
    						<option value="3"><?php /* @escapeNotVerified */ echo __("Value three"); ?></option>
    						<option value="4"><?php /* @escapeNotVerified */ echo __("Value four"); ?></option>
    						<option value="5"><?php /* @escapeNotVerified */ echo __("Value five"); ?></option>
    					</select>
    				</div>
    		</div>
    	</form>
    </fieldset>
    
    <!-- inititializing the javascript -->
    <script type="text/x-magento-init">
        {
            "*":{
                "mselectjs":{
                    "somData": {
                    	"myElement": ".myElement"
                    }
                }
            }
        }
    </script>

    Now we will create a require js config file to register our js component at app/code/Webkul/MultiSelect/view/frontend/requirejs-config.js:

    var config = {
        map: {
            '*': {
               
                mselectjs: 'Webkul_MultiSelect/js/mselect'
    
            }
        }
    };

    Now we will create our component file that will reside all the logic and components for multi-select :

    app/code/Webkul/MultiSelect/view/frontend/web/js/mselect.js :

    // js file to apply multiselect js
    
    define(
        [
          'jquery',
          'mage/translate',
          'Magento_Ui/js/modal/alert',
          'Magento_Ui/js/modal/confirm',
          'mage/mage',
          'jquery/ui',
          'jquery/editableMultiselect/js/jquery.editable',
          'jquery/editableMultiselect/js/jquery.multiselect'
    
        ], function($,$t,alert,confirm) {
     
        $.widget(
            'webkul.mselect', {
                _create: function() {
                    var self = this;
                  
                    /**
                     * intialize multi select for demo tax field
                     */
                    $(self.options.somData.myElement)
                        .multiselect({
                        toggleAddButton:false,
                        addText: $t('Add New Option'),
                        parse: null,
                        mselectInputSubmitCallback:function(value,options) {
                          $('body').trigger('processStart');
                          var select = $(self.options.somData.myElement);
                            /**
                             * Do your stuff here like saving in the database etc
                             */
                            response = self.addNewOption(value);
    
                                /**
                                 * Create the html to add in your multiselect
                                 */
                                select.append('<option value="'+value+'" selected="selected">' + value + '</option>');
                                var mselectItemHtml = $(options.item.replace(/%value%/gi, value)
                                .replace(/%label%/gi, value)
                                .replace(/%mselectDisabledClass%|%iseditable%|%isremovable%/gi, '')
                                .replace(/%mselectListItemClass%/gi, options.mselectListItemClass))
                                .find('[type=checkbox]')
                                .attr('checked', true)
                                .end();
                                var itemsWrapper = select.nextAll('section.block:first')
                                .find('.' + options.mselectItemsWrapperClass + '');
                                itemsWrapper.children('.' + options.mselectListItemClass + '').length
                                ? itemsWrapper.children('.' + options.mselectListItemClass + ':last').after(mselectItemHtml)
                                : itemsWrapper.prepend(mselectItemHtml);
                                $('body').trigger('click');
                                $('body').trigger('processStop');
                      },
                    }).parent().find('.mselect-list')
                    .on(
                        'click.mselect-edit', 
                        '.mselect-edit', 
                        function(){
                          $('body').trigger('processStart');
                          self.editOption($(this));
                          $('body').trigger('processStop');
                        }
                    )
                    .on(
                        "click.mselect-delete", 
                        ".mselect-delete",
                        function(){
                          $('body').trigger('processStart');
                          var optionId = $(this).parent().find('label').find('input').val();
                          self.deleteOption();
                          $(this).parents('.mselect-list-item').remove();
                          $("#tax_customer_class option[value='"+optionId+"']").remove();
                          $('body').trigger('processStop');
                        }
                    );
            },
    
            /**
             * addNewOption implement you login here to add new option
             * @param value new option value
             */
            addNewOption: function(value) {
              // implement your login here to do your processing with the value
              
              return $.trim(value);
    
              
            },
    
            /**
             * editOption function to work with edit option
             */
            editOption: function(element) {
              // implement your logic here to do your processing
              var self = element.parent().find('label');
              var editOption = self.find('span');
    
              /**
               * url ajax url for updating option value
               * @type String
               */
              url = ""
              /**
               * override ajax options with your own
               * @type {Object}
               */
              var ajaxoptions = {
                  success : function(result, status) {
                      editOption.html("YOUR RESULT");
                  },
              };
    
              /**
               * editable is a jquery.editable function which is used for inline 
               * editing it requires two params ajax url and object, the objct has 
               * many options please refer to jquery.editable js 
               */
              element.parent().find('label').find('span').editable(
                  url,
                  {
                      type:'text',
                      submitdata: {},
                      ajaxoptions: ajaxoptions,
                      indicator: "Updating...",
                      name:'class_name',
                      data:function(value,setting) {
    
                          return editOption.html(); 
                      },
                      onerror: function(settings, original, xhr) {
                          alert({content:$t("error occured not able to update class name")});
                      }
                  }
              );
              editOption.trigger('click');
              editOption.editable('destroy');
              
            },
    
            deleteOption: function() {
              // implement your login here to on dele option
              alert({content: $t("Delete the option create your logic")});
            }
    
          }
             
        );
     
            return $.webkul.mselect;
        }
    );

    All the files that are created here are very general and you have to create those when you create any module, so I am only going to explain to you the mselect.js file, in the js file we have used jquery widgets, Now we will see what are these methods and their use:

    define: define is used to register the js libraries within the scope of the function, its first parameter is an array of js libraries and the second is the function that will contain the logic. In the array of js libraries two libraries in the last :

    ‘jquery/editableMultiselect/js/jquery.editable’ : this  library is used for inline editing of the values
    ‘jquery/editableMultiselect/js/jquery.multiselect’: this library is used to add a multi-select select box to a beautiful multi select with all the edit, and delete add options.

    Now the second param is the function inside the function we have created a jQuery widget “webkul.mselect”

    in this widget we have created many methods, they are explained below:

    _create : this method of the widget is used to initialize the widget here we have added the multiselect on the multiselect element, the method used to initialize multiselect on the element is “multiselect” , this method accepts one parameter an object with key value pairs , in those “mselectInputSubmitCallback” this key has a function which is called when we try to add a new option in the multiselect .

    and all the other three methods are the helper methods for the multiselect events edit, add, delete events .

    After applying the multiselect your multiselect will look like this :

    multiselect

    Finally, you need to login as a customer and hit this URL:

    {YOUR BASE URL}/multiselect/multiselect/demo/

    I hope you like this, like multi-select there is lots of great features of Magento 2 that we are still exploring, I will try to explore more rich features of Magento 2 and post them here.

    If you have any doubts in the above code, you can ask in the comments below.

    Thanks 🙂

    . . .

    Leave a Comment

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


    1 comments

  • sethhu
  • Back to Top

    Message Sent!

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

    Back to Home