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

Select2Entity Bundle Laravel Package

tetranz/select2entity-bundle

Symfony bundle integrating Select2 with Doctrine entities: AJAX search, dynamic loading, and autocompletion for entity fields in forms. Supports remote endpoints, custom queries, pagination, and transforming selections to entities for smooth UX.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require tetranz/select2entity-bundle
    

    Add to config/bundles.php:

    return [
        // ...
        Tetranz\Select2EntityBundle\TetranzSelect2EntityBundle::class => ['all' => true],
    ];
    
  2. Basic Usage in a Form

    use Tetranz\Select2EntityBundle\Form\Type\Select2EntityType;
    
    $builder->add('user', Select2EntityType::class, [
        'class' => User::class,
        'property' => 'fullName', // Display property
        'multiple' => false,
    ]);
    
  3. First Use Case Replace a standard EntityType field in a form with Select2EntityType for an enhanced UX with search/filtering.


Implementation Patterns

Common Workflows

  1. Basic Entity Selection

    $builder->add('role', Select2EntityType::class, [
        'class' => Role::class,
        'property' => 'title',
    ]);
    
  2. Multiple Selection

    $builder->add('tags', Select2EntityType::class, [
        'class' => Tag::class,
        'property' => 'name',
        'multiple' => true,
    ]);
    
  3. Custom Query Builder

    $builder->add('project', Select2EntityType::class, [
        'class' => Project::class,
        'query_builder' => function (EntityManagerInterface $em) {
            return $em->getRepository(Project::class)
                ->createQueryBuilder('p')
                ->where('p.isActive = :active')
                ->setParameter('active', true);
        },
        'property' => 'name',
    ]);
    
  4. Integration with Symfony Forms

    • Works seamlessly with FormBuilder and FormType classes.
    • Supports all standard Symfony form options (e.g., required, label, attr).
  5. Twig Integration

    {{ form_row(form.user) }}
    

    Ensure select2 JavaScript is loaded (see Gotchas).


Advanced Patterns

  1. Dynamic Dependencies Use onChange events to dynamically update other fields:

    $('#form_user').on('change', function(e) {
        const userId = $(this).val();
        // Fetch related data via AJAX
    });
    
  2. Custom Templates Override the default template in templates/TetranzSelect2EntityBundle/form/fields.html.twig.

  3. Lazy Loading Use ajax configuration for large datasets:

    $builder->add('user', Select2EntityType::class, [
        'ajax' => [
            'url' => $this->generateUrl('app_user_autocomplete'),
            'data' => ['id' => 'js-user-id'],
        ],
    ]);
    
  4. Validation Combine with Symfony validators (e.g., @Assert\Valid or custom constraints).


Gotchas and Tips

Common Pitfalls

  1. JavaScript Dependencies

    • Ensure select2 JS/CSS is loaded after the form field:
      {{ parent() }}
      {{ form_widget(form) }}
      {{ include('TetranzSelect2EntityBundle::select2.js') }}
      
    • If using Webpack Encore, add:
      import 'select2';
      
  2. Entity Manager Injection

    • If using query_builder, ensure the EntityManagerInterface is injected into your form type or service.
  3. Multiple Fields with Same Class

    • Use unique attr options (e.g., attr => ['class' => 'select2-user']) to avoid conflicts.
  4. Translation Issues

    • Default labels (e.g., "Search") may not be translated. Override in your translation files:
      # messages.en.yml
      tetranz_select2_entity.search: "Search users..."
      
  5. Performance with Large Datasets

    • Use ajax mode or query_builder with pagination/filtering:
      'query_builder' => function (EntityManagerInterface $em) {
          return $em->getRepository(User::class)
              ->createQueryBuilder('u')
              ->setMaxResults(50);
      },
      

Debugging Tips

  1. Check Console for Errors

    • Look for Uncaught ReferenceError: Select2 is not defined (missing JS).
    • Verify data-select2-entity attributes are rendered in HTML.
  2. Inspect Network Requests

    • For ajax mode, check if the endpoint returns valid JSON:
      [
          {"id": 1, "text": "John Doe"},
          {"id": 2, "text": "Jane Smith"}
      ]
      
  3. Clear Cache

    php bin/console cache:clear
    

    If templates or configurations aren’t updating.

Extension Points

  1. Customize Select2 Options Pass options via select2_options:

    $builder->add('user', Select2EntityType::class, [
        'select2_options' => [
            'width' => '100%',
            'placeholder' => 'Select a user...',
            'minimumInputLength' => 2,
        ],
    ]);
    
  2. Override Templates Copy templates/TetranzSelect2EntityBundle/form/fields.html.twig to your bundle’s Resources/views/ and customize.

  3. Add Custom Data Attributes

    $builder->add('user', Select2EntityType::class, [
        'attr' => ['data-custom' => 'value'],
    ]);
    
  4. Event Listeners Attach JavaScript events via attr:

    $builder->add('user', Select2EntityType::class, [
        'attr' => [
            'data-on-select' => 'handleUserSelect',
        ],
    ]);
    
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.
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
directorytree/privacy-filter-classifier
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata
splash/openapi