Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Select2 Bundle Laravel Package

ecommit/select2-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. 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],
    ];
    
  2. 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>
    
  3. 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
    ]);
    

Implementation Patterns

Common Workflows

  1. 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" }]
    
  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
    ]);
    
  3. 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 %}
    
  4. 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.


Gotchas and Tips

Pitfalls

  1. Asset Loading Conflicts

    • Issue: Select2 fails to initialize if jQuery or Select2 JS/CSS are loaded multiple times.
    • Fix: Use {{ encore_entry_link_tags() }} or bundle assets via Webpack Encore to avoid duplicates.
  2. AJAX Data Format Mismatch

    • Issue: Select2 expects id/text keys by default. Custom formats may break rendering.
    • Fix: Use 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));
      
  3. Multiple Select2 Fields on One Page

    • Issue: Select2 may conflict if multiple instances share the same namespace.
    • Fix: Use unique data-select2-id attributes in Twig:
      {{ form_widget(form.field, {'attr': {'data-select2-id': 'unique-id'}}) }}
      
  4. Deprecated Select2 Versions

    • Issue: The bundle may not align with the latest Select2 (v4.x) features.
    • Tip: Check the bundle’s composer.json for locked versions. Override via:
      composer require select2:^4.1 --dev
      

Debugging Tips

  • Inspect Rendered HTML: Verify data-select2-* attributes are present.
  • Check Console Errors: Look for Uncaught TypeError (e.g., missing jQuery).
  • Enable Select2 Debug Mode: Add to your JS:
    $.fn.select2.defaults.set('debug', true);
    

Extension Points

  1. Custom Events Listen to Select2 events via JavaScript:

    $('#your-select').on('select2:select', function(e) {
        console.log('Selected:', e.params.data);
    });
    
  2. Server-Side Processing Use the data option to pass parameters:

    'ajax' => [
        'url' => '/api/search',
        'data' => ['type' => 'advanced'],
    ]
    
  3. Localization Override translations in config/packages/ecommit_select2.yaml:

    twig:
        select2:
            search_placeholder: "Buscar..."
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
calmfox/watch-sylius
damienfern/grpc-symfony-bundle
atoolo/index-bundle
atoolo/genai-bundle
coprotoai/laravel-ticket
davidjln/llm-carbon-bundle
cryonighter/valid-request-bundle
coolms/taxonomy-bundle
coolms/field-bundle
articulate-orm/symfony
aaix/laravel-tall-architect
ephoto/akeneo-connector
emmanuelballery/eb-plantumlbundle
emielburgman/symfony-visitor-beacon
emielburgman/symfony-visit-storage
emielburgman/symfony-security-headers
emielburgman/symfony-log-viewer
emarref/xdebug-bundle
emarref/pubnub-bundle
elriseio/finance-money-bundle