Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Integrating Select2 with Magento 2

I'm trying to integrate Select2 with Magento2. So far I have integrated the plugin successfully but there are errors showing on the console. enter image description here

What I've done:

  1. Downloaded the select2.min.js and put it in app/design/frontend/<vendor>/<themename>/web/js/select2.min.js
  2. Included the script in app/design/frontend/<vendor>/<themename>/Magento_Theme/layout/default_head_blocks.xml
  3. Added this to the phtml file in script tags:

    require(['jquery'],function(jquery){ jquery(document).load(function() { jquery("#sorter2").select2(); }); });

I know I should it include it via requireJS but I can't seem to make it work.

Thanks!

like image 743
Ian Avatar asked Jan 16 '17 08:01

Ian


1 Answers

You shouldn't add it in the header on every page as it's dependencies won't necessarily load. You need to add it to your themes requirejs-config here;

/app/design/frontend/<vendor>/<theme>/requirejs-config.js

In the file put this;

var config = {
    paths: {
        'select2': 'js/select2.min',
    },
};

Now in any phtml file you can call it like this;

<script type="text/javascript">
    require(['jquery','select2'],function($){
        // do stuff with select
    });
</script>
like image 121
PixieMedia Avatar answered Sep 19 '22 13:09

PixieMedia