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

Choosy Type Laravel Package

braunstetter/choosy-type

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require braunstetter/choosy
    

    Ensure Encore (Webpack Encore) is configured in your Laravel project (this package relies on frontend assets).

  2. First Use Case: Add ChoosyType to a form builder in a controller or form class:

    use Braunstetter\ChoosyBundle\Form\Type\ChoosyType;
    
    $form = $this->createFormBuilder()
        ->add('tags', ChoosyType::class, [
            'choices' => [
                'Option 1' => 'value1',
                'Option 2' => 'value2',
            ],
        ])
        ->getForm();
    
  3. Frontend Setup: Run the provided Yarn commands (from the README) to compile assets:

    yarn --cwd ./vendor/braunstetter/choosy/src/Resources/assets install --force
    yarn --cwd ./vendor/braunstetter/choosy/src/Resources/assets dev
    

    Ensure the compiled JS/CSS is included in your layout (e.g., via @braunstetter_choosy/styles in your Webpack entry).


Implementation Patterns

Common Workflows

  1. Basic Tag Picker: Use ChoosyType for simple key-value choices (e.g., predefined tags):

    $builder->add('predefinedTags', ChoosyType::class, [
        'choices' => ['Admin' => 'admin', 'User' => 'user'],
        'multiple' => true, // Enable multi-select
    ]);
    
  2. Entity-Based Picker: Use ChoosyEntityType for dynamic database-backed options (e.g., fetching tags from a Tag model):

    $builder->add('dynamicTags', ChoosyEntityType::class, [
        'class' => Tag::class,
        'property' => 'name', // Display property
        'multiple' => true,
    ]);
    
  3. Customizing Choosy Options: Pass JavaScript options directly (see Choosy docs):

    $builder->add('searchableTags', ChoosyType::class, [
        'choices' => [],
        'options' => [
            'js_options' => [
                'search' => true,
                'placeholder' => 'Search tags...',
            ],
        ],
    ]);
    
  4. Integration with Form Events: Dynamically populate choices via PRE_SET_DATA or PRE_SUBMIT:

    $builder->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) {
        $data = $event->getData();
        $choices = $this->tagRepository->findByUser($data->getUser());
        $event->getForm()->add('tags', ChoosyType::class, [
            'choices' => $choices,
        ]);
    });
    
  5. Validation: Use Symfony’s validation constraints (e.g., NotBlank, Valid) alongside Choosy:

    $builder->add('requiredTags', ChoosyType::class, [
        'choices' => [],
        'constraints' => [
            new NotBlank(),
        ],
    ]);
    

Gotchas and Tips

Pitfalls

  1. Asset Compilation:

    • Issue: Frontend assets may not load if Webpack Encore is misconfigured or not run.
    • Fix: Ensure yarn dev (or yarn build) is executed after installation. Check your webpack.mix.js includes:
      mix.encore
          .addEntry('choosy', './vendor/braunstetter/choosy/src/Resources/assets/js/choosy.js')
          .copyDirectories(['./vendor/braunstetter/choosy/src/Resources/public', 'public/build']);
      
  2. EntityType Dependencies:

    • Issue: ChoosyEntityType requires Doctrine ORM (or a compatible entity manager).
    • Fix: Ensure your Tag entity (or similar) is properly mapped and the class option points to a valid entity class.
  3. JavaScript Conflicts:

    • Issue: Choosy’s jQuery dependency may conflict with other plugins.
    • Fix: Isolate Choosy in a unique namespace or use js_options to customize selectors:
      'options' => [
          'js_options' => [
              'selector' => '.my-choosy-picker',
          ],
      ],
      
  4. Empty Choices:

    • Issue: Passing an empty choices array may break rendering.
    • Fix: Validate choices in PRE_SET_DATA or provide a fallback:
      $builder->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) {
          $form = $event->getForm();
          $choices = $event->getData()['choices'] ?? [];
          if (empty($choices)) {
              $form->add('tags', ChoosyType::class, ['choices' => []]);
          }
      });
      

Debugging Tips

  1. Check Compiled Assets: Verify the Choosy JS/CSS is output in your template:

    {{ encore_entry_script_tags('choosy') }}
    {{ encore_entry_link_tags('choosy') }}
    
  2. Inspect Browser Console: Look for errors like Choosy is not defined (missing JS) or 404 (asset paths).

  3. Symfony Profiler: Use the profiler to inspect form data and submitted values for debugging:

    dump($form->getData());
    

Extension Points

  1. Custom Templates: Override the default Twig template by setting the template option:

    $builder->add('tags', ChoosyType::class, [
        'template' => '@YourBundle/choosy/custom_template.html.twig',
    ]);
    
  2. Dynamic Choices via AJAX: Use js_options to fetch choices dynamically:

    'options' => [
        'js_options' => [
            'ajax' => [
                'url' => '/api/tags',
                'dataType' => 'json',
            ],
        ],
    ],
    
  3. Event Listeners: Extend functionality with form events (e.g., post-submit processing):

    $builder->addEventListener(FormEvents::SUBMIT, function (FormEvent $event) {
        $data = $event->getData();
        // Process Choosy-submitted data (e.g., normalize values)
    });
    
  4. Localization: Customize labels/placeholders via translation domains:

    # config/packages/braunstetter_choosy.yaml
    braunstetter_choosy:
        default_options:
            js_options:
                placeholder: '{{ "choosy.placeholder"|trans }}'
    
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.
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager