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

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your answer we can also create class="selectsymfony" for all select form and in my JS i make $('selectsymfony').select2(); and in your answer you forget "]" in ('select[data-select="true"') ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.