Reputation: 885
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:
Upvotes: 3
Views: 11002
Reputation: 7902
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.
Upvotes: 2