Install the Bundle
Add the bundle to your composer.json:
composer require e-commit/select2-bundle
Register the bundle in config/bundles.php:
return [
// ...
Ecommit\Select2Bundle\EcommitSelect2Bundle::class => ['all' => true],
];
Enable JavaScript & CSS
Ensure Select2 assets are loaded in your base template (e.g., base.html.twig):
{{ encore_entry_link_tags('app') }} {# or manually include #}
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/select2.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/select2.min.js"></script>
First Use Case: Basic Select2 Field
In a form type (e.g., YourFormType):
use Ecommit\Select2Bundle\Form\Type\Select2Type;
$builder->add('users', Select2Type::class, [
'choices' => ['user1' => 'John', 'user2' => 'Jane'],
'placeholder' => 'Select a user',
'multiple' => true, // Optional
]);
Dynamic Data Loading (AJAX)
Use the ajax option to fetch remote data:
$builder->add('tags', Select2Type::class, [
'ajax' => [
'url' => '/api/tags',
'data' => ['min_length' => 2],
],
'placeholder' => 'Search tags...',
]);
Note: Ensure your endpoint returns JSON in Select2’s expected format:
[{ "id": 1, "text": "Tag 1" }, { "id": 2, "text": "Tag 2" }]
Integration with Symfony Forms Extend existing form types:
$builder->add('roles', Select2Type::class, [
'choices' => $this->getRoles(), // From a service/repo
'choice_label' => 'name', // Custom label property
'choice_value' => 'id', // Custom value property
]);
Custom Templates Override the default Twig template for full control:
{% extends 'EcommitSelect2Bundle::select2_widget.html.twig' %}
{% block select2_options %}
{{ parent() }}
data-minimum-results-for-search: 5
{% endblock %}
Validation & Error Handling Combine with Symfony’s validation:
$builder->add('category', Select2Type::class, [
'choices' => $categories,
'constraints' => [new NotBlank()],
]);
Errors render automatically via Symfony’s form theme.
Asset Loading Conflicts
{{ encore_entry_link_tags() }} or bundle assets via Webpack Encore to avoid duplicates.AJAX Data Format Mismatch
id/text keys by default. Custom formats may break rendering.choice_label/choice_value or pre-process data in the controller:
return response()->json(array_map(fn($item) => [
'id' => $item['id'],
'text' => $item['name'],
], $items));
Multiple Select2 Fields on One Page
data-select2-id attributes in Twig:
{{ form_widget(form.field, {'attr': {'data-select2-id': 'unique-id'}}) }}
Deprecated Select2 Versions
composer.json for locked versions. Override via:
composer require select2:^4.1 --dev
data-select2-* attributes are present.Uncaught TypeError (e.g., missing jQuery).$.fn.select2.defaults.set('debug', true);
Custom Events Listen to Select2 events via JavaScript:
$('#your-select').on('select2:select', function(e) {
console.log('Selected:', e.params.data);
});
Server-Side Processing
Use the data option to pass parameters:
'ajax' => [
'url' => '/api/search',
'data' => ['type' => 'advanced'],
]
Localization
Override translations in config/packages/ecommit_select2.yaml:
twig:
select2:
search_placeholder: "Buscar..."
How can I help you explore Laravel packages today?