Winter CMS resources and help articles

Simple and to the point. Optimized by the community.

AJAX requests in Plugin Settings

1
by AIC BV, last modified on October 7th, 2024
  1. Create your Settings plugin as usual, but use the url instead of class property at the registerSettings method.
  2. Create a controller: Settings.php:
<?php namespace Author\Plugin\Controllers;
use Backend\Classes\Controller;

use Backend;
use Redirect;
use BackendMenu;
use System\Classes\SettingsManager;
use Winter\Storm\Router\Helper as RouterHelper;

class Settings extends Controller
{

    public $implement = [
        \Backend\Behaviors\FormController::class
    ];

    public $formConfig = [
        'name' => 'Settings',
        'form' => "$/author/plugin/models/settings/fields.yaml",
        'modelClass' => 'Author\Plugin\Models\Settings',
        'defaultRedirect' => 'author/plugin/settings/update/:id',
    ];

    public function __construct()
    {
        parent::__construct();
        BackendMenu::setContext('Winter.System', 'system', 'settings');
        SettingsManager::setContext('Author.Plugin', 'settings');
    }

    /* NEEDED FOR SETTINGS PAGE COMBINED WITH AJAX EVENTS */
    public function index()
    {
        return $this->update();
    }

    public function create()
    {
        return $this->update();
    }

    public function update($id=null)
    {
        if (is_null($id)) {
            $model = $this->formCreateModelObject();
            $model = $model->firstOrCreate(['item' => $model->settingsCode]);

            $redirectUrl = RouterHelper::replaceParameters($model, $this->formGetRedirectUrl('update', $model));
            return Backend::redirect($redirectUrl);
        }

        return parent::update($id);
    }
    /* END */

    public function onMyFunction()
    {
    }

}
  1. Create settings folder in controllers folder with update.htm:
<?php Block::put('breadcrumb') ?>
    <ul>
        <li><?= e($this->pageTitle) ?></li>
    </ul>
<?php Block::endPut() ?>

<?= Form::open(['class' => 'layout']) ?>

    <div class="layout-row">
        <?= $this->formRender() ?>
    </div>

    <div class="form-buttons">
        <div class="loading-indicator-container">
            <button
                type="submit"
                data-request="onSave"
                data-request-data="redirect:0"
                data-hotkey="ctrl+s, cmd+s"
                class="btn btn-primary">
                <u>S</u>ave
            </button>
        </div>
    </div>

<?= Form::close() ?>

Now you can call your Ajax functions.

Discussion

0 comments

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