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

Stimulus Controller Bundle Laravel Package

amorebietakoudala/stimulus-controller-bundle

View on GitHub
Deep Wiki
Context7
## Getting Started

### Minimal Setup
1. **Install the Bundle**
   Add the package via Composer:
   ```bash
   composer require amorebietakoudala/stimulus-controller-bundle

Enable the bundle in config/bundles.php:

Amorebietakoudala\StimulusControllerBundle\AmorebietakoudalaStimulusControllerBundle::class => ['all' => true],
  1. Configure Webpack Encore Ensure webpack.config.js includes the bundle’s Stimulus controllers:

    Encore
        .addEntry('app', './assets/app.js')
        .enableStimulusBridge('./vendor/amorebietakoudala/stimulus-controller-bundle')
        .splitEntry();
    

    Run yarn encore dev to compile assets.

  2. First Use Case: Table Controller Use the table controller to handle row actions (e.g., delete, edit) with minimal JS:

    <table data-controller="table" data-table-url-value="/api/items">
        <tr data-table-target="row" data-table-id-value="1">
            <td>Item 1</td>
            <td>
                <button data-action="click->table#delete" data-table-confirm-value="Are you sure?">
                    Delete
                </button>
            </td>
        </tr>
    </table>
    

    Define the delete action in your controller (e.g., app/controllers/table_controller.js):

    import { Controller } from '@hotwired/stimulus';
    
    export default class extends Controller {
        static targets = ['row'];
        static values = { url: String, id: Number, confirm: String };
    
        delete() {
            if (!this.confirmValue || confirm(this.confirmValue)) {
                fetch(`${this.urlValue}/${this.idValue}`, { method: 'DELETE' })
                    .then(() => this.rowTarget.remove());
            }
        }
    }
    

Implementation Patterns

Common Workflows

  1. Dynamic Form Actions Use the action-changer controller to dynamically update form actions (e.g., for multi-step forms):

    <form data-controller="action-changer" data-action-changer-url-value="/submit">
        <button type="submit" data-action-changer-target="submitter" data-action="click->action-changer#submit">
            Submit
        </button>
    </form>
    
    // app/controllers/action_changer_controller.js
    export default class extends Controller {
        static targets = ['submitter'];
        static values = { url: String };
    
        submit() {
            this.submitterTarget.form.action = this.urlValue;
        }
    }
    
  2. Collection Management Manage Symfony Collection fields (e.g., for nested forms) with the collection controller:

    <div data-controller="collection" data-collection-url-value="/items">
        <template data-collection-target="template">
            <div data-collection-target="item">
                <input name="items[0][name]" />
                <button data-action="click->collection#remove">Remove</button>
            </div>
        </template>
        <button data-action="click->collection#add">Add Item</button>
    </div>
    
  3. Select2 Integration Enhance <select> elements with autofocus and AJAX loading:

    <select data-controller="select2"
            data-select2-url-value="/api/tags"
            data-select2-autofocus-value="true">
        <option value="">Choose...</option>
    </select>
    
  4. Entity CRUD Use the entity controller for RESTful operations on single resources:

    <div data-controller="entity" data-entity-url-value="/api/item/1">
        <button data-action="click->entity#update">Save</button>
    </div>
    

Integration Tips

  • Laravel Backend: Pair controllers with Laravel routes (e.g., Route::delete('/api/items/{id}', [ItemController::class, 'destroy'])).
  • Webpack Encore: Ensure stimulus-bridge is enabled for Stimulus controllers to work with Laravel’s asset pipeline.
  • Custom Controllers: Extend existing controllers (e.g., table_controller.js) by overriding methods or adding new targets/values.
  • Testing: Use Laravel’s StimulusTestCase or Jest to test Stimulus controllers in isolation.

Gotchas and Tips

Pitfalls

  1. Webpack Encore Version Mismatch

    • Issue: The bundle requires webpack-encore-bundle v1.11 or v2.1. Using an incompatible version may break asset compilation.
    • Fix: Update Encore or check the bundle’s composer.json for compatibility:
      composer require symfony/webpack-encore-bundle:^2.1
      
  2. Missing Stimulus Bridge

    • Issue: Forgetting to enable enableStimulusBridge() in webpack.config.js will prevent controllers from loading.
    • Fix: Add the bridge path explicitly:
      Encore.enableStimulusBridge('./vendor/amorebietakoudala/stimulus-controller-bundle');
      
  3. Data Attributes Not Binding

    • Issue: Stimulus targets/values not updating due to incorrect data-* attributes (e.g., data-table-id-value vs. data-table-id).
    • Fix: Verify attribute names match the controller’s static targets/values (e.g., data-table-id-value for id: Number).
  4. CSRF Token in AJAX Requests

    • Issue: Forgetting to include Laravel’s CSRF token in fetch requests may cause 419 errors.
    • Fix: Add the token to headers:
      fetch(url, {
          method: 'DELETE',
          headers: {
              'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content,
          },
      });
      
  5. Select2 Dependencies

    • Issue: Select2 may fail to load if its CSS/JS isn’t included.
    • Fix: Add to webpack.config.js:
      Encore.addEntry('select2', './node_modules/select2/dist/js/select2.js')
            .enablePostCssLoader()
            .copyFiles({
                from: './node_modules/select2/dist/css/',
                to: 'css/[path][name].css',
            });
      

Debugging Tips

  • Check Stimulus Logs: Enable debug mode in app.js:
    import { Application } from '@hotwired/stimulus';
    const application = Application.start();
    application.debug = true; // Logs controller lifecycle events
    
  • Verify Controller Registration: Ensure controllers are compiled into app.js. Check the Webpack output for errors.
  • Inspect Data Attributes: Use browser dev tools to confirm data-* attributes are correctly set on elements.

Extension Points

  1. Custom Controllers Extend existing controllers by creating new files in app/controllers/ (e.g., custom_table_controller.js):

    import { Controller } from '@hotwired/stimulus';
    import { TableController } from 'stimulus-controller-bundle';
    
    export default class extends TableController {
        connect() {
            super.connect();
            console.log('Custom Table Controller initialized');
        }
    }
    
  2. Override Defaults Use the options value to override controller defaults (e.g., for the table controller):

    <table data-controller="table"
           data-table-options-value='{"confirm": "Custom message"}'>
    
  3. Add New Actions Extend controllers with additional methods (e.g., add a preview action to entity_controller.js):

    preview() {
        fetch(`${this.urlValue}/preview`)
            .then(response => response.text())
            .then(html => document.getElementById('preview').innerHTML = html);
    }
    
  4. Global Configuration Centralize Stimulus settings in app.js:

    application.register('global', {
        connect() {
            // Shared logic (e.g., CSRF token handling)
        },
    });
    

Configuration Quirks

  • Autofocus Behavior: The select2 controller enables autofocus by default. Disable it with:
    <select data-select2-autofocus-value="false">
    
  • Table Row IDs: Ensure data-table-id-value matches the backend’s resource ID (e.g., database id field).
  • Return URLs: For the table controller’s delete action, specify a data-table-return-url-value to redirect after deletion.

Performance

  • Lazy-Load Controllers: Use dynamic imports for non-critical controllers to reduce initial bundle size:
    import('./controllers/custom_controller.js').then(module => {
        application.register('custom', module.default);
    });
    
  • Debounce Events: For controllers with frequent actions (e.g., collection add/remove), debounce events to avoid rapid API calls:
    let debounceTimer;
    
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.
besmartand-pro/php-quality-config
sentix/ai-chatbot
codifyo/ts-generator-bundle
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor