Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Integrate Select2 JS in Symfony 3

I will show you how to integrate Select2 in a Symfony3 project!

First, Add those 3 links to base.html.twig page.

<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.2/css/select2.min.css" rel="stylesheet" />
<link href ="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-beta1/jquery.min.js" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.2/js/select2.min.js"></script>

Second, In CompanyType.php add:

 use Symfony\Bridge\Doctrine\Form\Type\EntityType;

 class CompanyType extends AbstractType  {
     /**
      * @param FormBuilderInterface $builder
      * @param array $options
      */
     public function buildForm(FormBuilderInterface $builder, array $options)
     {
  $builder
        ->add('country',EntityType::class, array(
                 'attr'=>array('class'=>"country",),
                 'label'=>'Country of The Head fice',                     

                  'choices_as_values' => true, //               
                 'class' => 'QSCORBundle\Entity\CountryMaps',
                 'choice_label' => 'Country_Name',
 
             ))

    ->add(...)  
}
  ...
 }

after that, on ur Entity file Country.php add:

public function __toString()
    {
        // TODO: Implement __toString() method.

       return $this->getCountryName();
    }

Finally, in your template file xxx.html.twig write this:

<script type="text/javascript">
                $(document).ready(function() {
                        $(".country").select2();
                });
</script>
{{ form_widget(form.country)}}

Here is an image of how it looks like:

enter image description here

like image 541
Mourad MAMASSI Avatar asked Dec 05 '25 07:12

Mourad MAMASSI


1 Answers

You could also do this by adding a data attribute to your form builder element and then having a global JavaScript file that you include to your site to take care of the select2, no need to add it to each twig file.

For example;

$builder
    ->add('country', 'entity', [
        'class' => 'EntityType::class',
        'label'=>'Country of The Head fice',
        'choices_as_values' => true, //               
        'class' => 'QSCORBundle\Entity\CountryMaps',
        'choice_label' => 'Country_Name',
        'attr' => ['data-select' => 'true']
]);

Then in a site wide js file add;

$('select[data-select="true"]').select2();

That way any select that has a data attribute of data-select="true" will have select2 applied to it.

like image 99
Rooneyl Avatar answered Dec 06 '25 22:12

Rooneyl