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

Form Bundle Laravel Package

desarrolla2/form-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Add the bundle via Composer:

    composer require desarrolla2/form-bundle
    

    Enable the bundle in config/app.php under providers:

    Desarrolla2\FormBundle\FormBundle::class,
    
  2. Asset Registration Ensure the Select2 AJAX script is loaded in your layout (e.g., app.blade.php):

    <script src="{{ asset('vendor/desarrolla2/form-bundle/js/select2.ajax.js') }}"></script>
    
  3. First Use Case: Basic Select2 AJAX Field In a form (e.g., resources/views/form.blade.php), use the select2_ajax Twig helper:

    {{ form_widget(form.fields['example']) }}
    {{ form_label(form.fields['example']) }}
    {{ form_errors(form.fields['example']) }}
    
    <script>
        $('#example').select2_ajax({
            url: '{{ path('api_example_search') }}',
            data: function(term) {
                return { q: term };
            }
        });
    </script>
    
  4. API Endpoint Create a route and controller to handle AJAX requests (e.g., routes/api.php):

    Route::get('/example/search', [ExampleController::class, 'search'])->name('api_example_search');
    

    Controller method:

    public function search(Request $request)
    {
        $results = Model::where('name', 'like', '%'.$request->q.'%')->get();
        return response()->json($results);
    }
    

Implementation Patterns

Common Workflows

  1. Dynamic Data Fetching Use the select2_ajax JavaScript method to fetch and populate options dynamically:

    $('#dynamic_field').select2_ajax({
        url: '{{ path('api_search') }}',
        data: function(term, page) {
            return {
                q: term,
                page: page,
                per_page: 10
            };
        },
        results: function(data, page) {
            return { results: data.items, pagination: { more: data.has_more } };
        }
    });
    
  2. Integration with Symfony Forms Extend the FormType to include Select2 AJAX fields:

    use Desarrolla2\FormBundle\Form\Type\Select2AjaxType;
    
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('field_name', Select2AjaxType::class, [
            'ajax_url' => $options['ajax_url'],
            'choices' => $options['choices'] ?? [],
            'placeholder' => 'Select an option',
        ]);
    }
    
  3. Custom Templates Override the default Select2 template by extending the bundle’s Twig templates (located in Resources/views/Form/). Copy the template to templates/bundles/form/ in your project.

  4. Pagination and Loading States Configure loading indicators and pagination in the JavaScript:

    $('#field').select2_ajax({
        url: '{{ path('api_search') }}',
        loadingMore: function(element, data) {
            // Custom loading logic
        },
        loading: function(element) {
            element.parent().append('<div class="loading-indicator">Loading...</div>');
        }
    });
    
  5. Form Submission Handling Ensure the selected value is submitted correctly by binding the change event:

    $('#field').on('change', function() {
        $(this).closest('form').submit();
    });
    

Gotchas and Tips

Pitfalls

  1. Missing JavaScript File

    • Issue: Forgetting to include select2.ajax.js will break the AJAX functionality.
    • Fix: Verify the script is loaded in your layout or blade template.
  2. CORS Errors in AJAX Requests

    • Issue: If the API endpoint is on a different domain, CORS may block requests.
    • Fix: Configure CORS headers on the server or use a proxy.
  3. Incorrect Response Format

    • Issue: The select2_ajax method expects a specific JSON response format:
      {
          "results": [...],
          "pagination": { "more": true/false }
      }
      
    • Fix: Ensure your API returns data in this format. Use Laravel’s JsonResponse or manually format the response.
  4. Twig Helper Not Found

    • Issue: If using Twig helpers (e.g., form_widget), ensure the bundle is properly registered and Twig is configured to autoload it.
    • Fix: Clear the cache (php artisan cache:clear) and verify the bundle is enabled in config/app.php.
  5. Deprecated or Incompatible Dependencies

    • Issue: The bundle is archived and may rely on outdated versions of Select2 or Symfony.
    • Fix: Check for compatibility with your project’s dependencies. Consider forking the repository if critical updates are needed.

Debugging Tips

  1. Check Network Requests Use browser dev tools (Network tab) to verify AJAX requests are being sent and responses are received. Look for:

    • Correct URLs.
    • Proper HTTP status codes (e.g., 200 OK).
    • Valid JSON responses.
  2. Console Logs Add debug logs in JavaScript to trace execution:

    $('#field').select2_ajax({
        url: '{{ path('api_search') }}',
        debug: true // Logs requests/responses to console
    });
    
  3. Symfony Profiler Use Symfony’s profiler to inspect form data and submitted values during debugging.

Extension Points

  1. Custom AJAX Handlers Extend the JavaScript logic to handle custom responses or actions:

    $('#field').select2_ajax({
        url: '{{ path('api_search') }}',
        ajaxSetup: function(options) {
            options.beforeSend = function() {
                // Custom logic before sending the request
            };
            options.success = function(data) {
                // Custom logic after receiving the response
            };
        }
    });
    
  2. Server-Side Processing Add server-side validation or transformation in your API endpoint:

    public function search(Request $request)
    {
        $validated = $request->validate(['q' => 'required|string']);
        $results = Model::where('name', 'like', '%'.$validated['q'].'%')->get();
        return response()->json([
            'results' => $results,
            'pagination' => ['more' => $results->count() > 10]
        ]);
    }
    
  3. Localization Override the default Select2 labels or messages by extending the Twig templates or using JavaScript:

    $.fn.select2_ajax.defaults.ajax = {
        dataType: 'json',
        delay: 250,
        data: function(term) {
            return { q: term, locale: '{{ app()->getLocale() }}' };
        }
    };
    
  4. Integration with Laravel Mix/Webpack If using Laravel Mix, ensure the select2.ajax.js file is copied to public/js during the build process. Add it to your webpack.mix.js:

    mix.copy('node_modules/select2/dist/js/select2.ajax.js', 'public/js/');
    
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.
craftcms/url-validator
directorytree/privacy-filter-classifier
directorytree/privacy-filter
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
splash/scopes
splash/toolkit
testo/output-teamcity
testo/bridge-symfony