Weave 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

Select24Entity Bundle Laravel Package

brunops/select24entity-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require brunops/select24entity-bundle
    

    Add to bundles.php:

    Brunops\Select24EntityBundle\BrunopsSelect24EntityBundle::class => ['all' => true],
    
  2. Enable AJAX Endpoint: Configure a route for AJAX entity fetching (e.g., select2_ajax_entity):

    # config/routes.yaml
    select2_ajax_entity:
        path: /ajax/entity/{entityClass}
        defaults: { _controller: Brunops\Select24EntityBundle\Controller\Select2Controller::ajaxEntityAction }
    
  3. First Use Case: Replace a standard EntityType field in a form with Select2EntityType:

    use Brunops\Select24EntityBundle\Form\Type\Select2EntityType;
    
    $builder->add('user', Select2EntityType::class, [
        'class' => User::class,
        'ajax_route' => 'select2_ajax_entity',
        'placeholder' => 'Select a user...',
    ]);
    
  4. JavaScript Activation: Initialize Select2 manually in your JS (no auto-initialization):

    $(document).ready(function() {
        $('.select2').select2({
            ajax: {
                url: Routing.generate('select2_ajax_entity', { entityClass: 'App\Entity\User' }),
                dataType: 'json',
                delay: 250,
                data: function(params) {
                    return {
                        q: params.term,
                        page: params.page
                    };
                },
                processResults: function(data) {
                    return {
                        results: $.map(data.items, function(item) {
                            return { text: item.name, id: item.id };
                        })
                    };
                },
                cache: true
            },
            minimumInputLength: 1,
        });
    });
    

Implementation Patterns

Core Workflow

  1. Form Integration:

    • Replace EntityType with Select2EntityType for AJAX-driven entity selection.
    • Configure ajax_route to point to your custom controller (default: select2_ajax_entity).
    • Use multiple for many-to-many relationships (e.g., tags, roles).
  2. AJAX Controller Customization: Extend the default controller to filter entities dynamically:

    // src/Controller/Select2Controller.php
    namespace App\Controller;
    
    use Brunops\Select24EntityBundle\Controller\Select2Controller as BaseController;
    use App\Entity\User;
    use Symfony\Component\HttpFoundation\Request;
    
    class Select2Controller extends BaseController
    {
        public function ajaxEntityAction(Request $request, $entityClass)
        {
            $this->setEntityClass($entityClass);
            $this->setSearchField('name'); // Override default search field
            $this->setSearchMethod('contains'); // 'startsWith', 'contains', 'exact'
    
            return parent::ajaxEntityAction($request, $entityClass);
        }
    }
    
  3. Twig Integration: Render the field with Select2-ready classes:

    {{ form_widget(form.user, { 'attr': {'class': 'select2'} }) }}
    
  4. Dynamic Configuration: Pass options to Select2EntityType for runtime flexibility:

    $builder->add('tags', Select2EntityType::class, [
        'class' => Tag::class,
        'ajax_route' => 'select2_ajax_entity',
        'multiple' => true,
        'placeholder' => 'Add tags...',
        'attr' => ['data-minimum-input-length' => 2],
    ]);
    
  5. Event Listeners: Attach listeners to modify AJAX responses or form behavior:

    // src/EventListener/Select2EntityListener.php
    use Brunops\Select24EntityBundle\Event\Select2EntityEvent;
    use Symfony\Component\EventDispatcher\EventSubscriberInterface;
    
    class Select2EntityListener implements EventSubscriberInterface
    {
        public static function getSubscribedEvents()
        {
            return [
                Select2EntityEvent::PRE_AJAX => 'onPreAjax',
            ];
        }
    
        public function onPreAjax(Select2EntityEvent $event)
        {
            $query = $event->getQuery();
            $query->andWhere('u.enabled = :enabled')->setParameter('enabled', true);
        }
    }
    

Gotchas and Tips

Pitfalls

  1. No Auto-Initialization:

    • The bundle does not auto-initialize Select2. You must manually call .select2() in JavaScript.
    • Fix: Wrap initialization in $(document).ready() or use event delegation for dynamic forms.
  2. Route Configuration:

    • The default ajax_route (select2_ajax_entity) must match your route name exactly.
    • Fix: Verify routing with php bin/console debug:router and adjust ajax_route in the form type.
  3. Entity Class Naming:

    • The entityClass parameter in the AJAX route must be a fully qualified class name (e.g., App\Entity\User).
    • Fix: Use get_class($entity) or hardcode the FQCN in the route.
  4. Pagination Limits:

    • Select2 expects paginated results for large datasets. The bundle returns all results by default.
    • Fix: Implement pagination in your AJAX controller:
      $query->setMaxResults(10)->setFirstResult(($request->query->getInt('page') - 1) * 10);
      
  5. CORS Issues:

    • AJAX requests may fail if the bundle is used in a SPA or cross-domain context.
    • Fix: Configure CORS headers in your Symfony app or proxy requests.
  6. Form Theme Overrides:

    • The bundle uses Symfony’s default form themes. Custom themes may break Select2 integration.
    • Fix: Extend the default theme or use the provided select24entity block:
      {# templates/select24entity.html.twig #}
      <div class="select2-container {{ id }}">
          {{ form_widget(form, {'attr': {'class': 'select2'}}) }}
      </div>
      

Debugging Tips

  1. Check AJAX Responses:

    • Inspect network requests in DevTools (F12) to verify payloads and responses.
    • Ensure the response format matches Select2’s expectations:
      {
          "items": [
              {"id": 1, "text": "User 1", "name": "User 1"},
              {"id": 2, "text": "User 2", "name": "User 2"}
          ]
      }
      
  2. Log Queries:

    • Enable Doctrine logging to debug query performance:
      # config/packages/dev/doctrine.yaml
      doctrine:
          dbal:
              logging: true
              profiling: true
      
  3. Clear Cache:

    • After modifying the bundle or routes, clear the cache:
      php bin/console cache:clear
      

Extension Points

  1. Custom Data Transformers:

    • Override how entities are converted to Select2-compatible data:
      $builder->add('user', Select2EntityType::class, [
          'class' => User::class,
          'ajax_route' => 'select2_ajax_entity',
          'transformer' => function ($entity) {
              return [
                  'id' => $entity->getId(),
                  'text' => $entity->getFullName(),
                  'email' => $entity->getEmail(),
              ];
          },
      ]);
      
  2. Custom Templates:

    • Override the default template for the Select2 field:
      {# templates/brunops_select24entity/select2_entity_widget.html.twig #}
      <div class="custom-select2-wrapper">
          {{ form_widget(form, {'attr': {'class': 'select2-custom'}}) }}
      </div>
      
  3. Event Dispatching:

    • Extend functionality via events:
      • Select2EntityEvent::PRE_AJAX: Modify the query before execution.
      • Select2EntityEvent::POST_AJAX: Alter the response data.
      • Select2EntityEvent::PRE_SET_DATA: Transform form data before binding.
  4. Dependency Injection:

    • Inject services into the AJAX controller for dynamic behavior:
      use App\Service\CustomEntityService;
      
      class Select2Controller extends BaseController
      {
          public function __construct(private CustomEntityService $entityService) {}
      
          public function ajaxEntityAction(Request $request, $entityClass)
          {
              $this->setEntityClass($entityClass);
              $this->setSearchField($this->entityService->getSearchField($entityClass));
              // ...
          }
      }
      
  5. Lazy Loading:

    • For large datasets, implement lazy loading in the AJAX controller:
      public function ajaxEntityAction(Request $request, $entityClass)
      {
          $this->setEntityClass($entityClass);
          $query = $this->get
      
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.
coleus/frame
thtg88/journalism
filagora/filagora-ai-forums
rlacerda83/query-parser
socialdept/atp-orm
cboxdk/laravel-assistant-client
socialdept/atp-resolver
socialdept/tenant-domains
tautvydasr/blade-class-names
socialdept/color-scales
maherelgamil/controller
coleus/widgets
coleus/table
coleus/users
coleus/music
coleus/health
coleus/calendar
coleus/notes
coleus/support
coleus/settings