Ajax handler for backend select2 autocomplete

Hello, what is the ideal place to put a php ajax event handler for a select2 autocomplete custom widget?, knowing that this widget could be used in multiple place on the backend? Would it be possible to register a callback for the handler in a plugin boot function?
Thanks!

i think you already know answer… right… on plugin boot method, you can extend controller to always add dynamic method for your s2 ajax event

1 Like

Thanks for your answer. Maybe you have an idea on where to find an example of this? Thanks again!

Thanks for your help. Here I guess I need to use something like a

Event::listen(...

within the boot function as described in the doc. But I can’t see something more specific in this doc. Should I name the event the same way I call the handler on frontend?

for example extending backend controller… for FE may be similiar use case

\Backend\Classes\Controller::extend(function($controller) {
     $controller->addDynamicMethod('onYourMethod', function() use ($controller) {
          /// your logic for extend controller
     });
});

The best place for an action handler for your widget, is the widget itself!

you can define an onDoSomething function in your widget and set up the HTML markup like this:

<a href="javascript:;" data-request="<?= $this->getEventHandler('onDoSomething') ?>" title="Next page">Next</a>

The getEventHandler methods prefixes the handler name with the current widget slug, which makes it portable as long as the widget is correctly bound to the controller (form widgets usually are).

This is the example from the v2 docs: Widgets - October CMS - 2.x

It’s the same for v3: AJAX - October CMS - 3.x

2 Likes

Here is an example of a select box with dynamic options, maybe it helps:

<select
    class="form-control custom-select"
    style="width: 200px"
    data-handler="onGetSelectOptions"
    data-minimum-input-length="1"
    data-ajax--delay="300"
    data-request-data="foo: 'bar'">
</select>