Winter CMS resources and help articles

Simple and to the point. Optimized by the community.

Add AJAX handler to a Settings page without a custom Controller

4
by Maz, last modified on June 10th, 2021

When you are dealing with a plugin's Settings model, you'll probably use the default Settings controller by registering your model like so:

// Plugin.php
public function registerSettings()
{
    return [
        'settings' => [
            //...
            'class'       => \AuthorName\PluginName\Models\Settings::class,
        ]
    ];
}

If you need for any reason to add an AJAX handler to this controller, only for your Settings model, you can do it by extending the default controller:

// Plugin.php
public function boot()
{
    // Extends the default Settings controller
    \System\Controllers\Settings::extend(function (\System\Controllers\Settings $controller) {

        // Settings' index page doesn't have a formWidget initiated, abort instantly
        if (url()->current() === Backend\Facades\Backend::url('system/settings')) {
            return;
        }

        // Only for your Settings model
        if ($controller->formGetWidget()->model instanceof \AuthorName\PluginName\Models\Settings) {
            $controller->addDynamicMethod('onAjaxHandlerName', static function () use ($controller) {
                // Do whatever you want here
            });
        }
    });
}

You can then call this AJAX handler from a partial form field.

# /authorname/pluginname/models/settings/fields.yaml
fields:
    _ajax_button:
        type: partial
        path: $/authorname/pluginname/models/settings/ajax_button.htm
        span: left
<!-- /authorname/pluginname/models/settings/ajax_button.htm -->
<button type="button"
        class="btn btn-primary"
        data-request="onAjaxHandlerName"
        data-request-flash
>Call my ajax handler</button>

This trick can also be used to add basic form's event handler like get*Options on form's refresh field and so on.

Discussion

0 comments

We use cookies to measure the performance of this website. Do you want to accept these cookies?