Search code examples
jquerynpmjquery-select2symfony4

Select 2 Webpack-encore


I'm trying to use select2 with webpack-encore on my symphony4 project. My app.js file is loaded without problem but not select2 while i installed it .. I do not understand why it's not working at all ...

My html

    <head>
    {{ encore_entry_link_tags('app') }}
    {{ encore_entry_script_tags('app') }}
    </head>
    <body>
    <select>
    <option value="">--Please choose an option--</option>
    <option value="dog">Dog</option>
    <option value="cat">Cat</option>
    <option value="hamster">Hamster</option>
    </select>

My app.js

require('../css/app.css');

const $ = require('jquery');





console.log('Hello Webpackfdsfds Encore! Edit me in assets/js/app.js');

require('select2')

$('select').select2({ width: '100%', placeholder: "Select an Option", allowClear: true })

What it looks like https://i.sstatic.net/bdbhj.jpg

I would be grateful if you would help me


Solution

  • You can simply import the select2 CSS with a require :

    require('../css/app.css');
    const $ = require('jquery');
    console.log('Hello Webpackfdsfds Encore! Edit me in assets/js/app.js');
    
    require('select2')
    require('select2/dist/css/select2.css')
    $('select').select2({ width: '100%', placeholder: "Select an Option", allowClear: true })
    

    It also exists custom styles, like :

    • select2-bootstrap-theme
    • select2-bootstrap4-theme
    • select2-flat-theme
    • select2-metro

    You can install them with yarn.