Winter CMS resources and help articles

Simple and to the point. Optimized by the community.

Creating a standalone controller for a Settings model.

0
by mjauvin, last modified on June 4th, 2023

Create your controller:

plugins/author/plugin/controllers/Settings.php:

use Backend;
use BackendMenu;
use Winter\Storm\Router\Helper as RouterHelper;

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

    public $implement = [
        'Backend.Behaviors.FormController',
    ];

    public function __construct()
    {
        parent::__construct();

        BackendMenu::setContext('Author.Plugin', 'main-menu', 'settings');
    }

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

    public function update($id=null)
    {
        if (is_null($id)) {
            $model = $this->formCreateModelObject();
            $model = $model->where('item', $model->settingsCode)->first();
            $redirectUrl = RouterHelper::replaceParameters($model, $this->formGetRedirectUrl('update', $model));
            return Backend::redirect($redirectUrl);
        }                                                              
        return parent::update($id);
    }
}

And a view for the update action:

plugins/author/plugin/controllers/settings/update.php:

<?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() ?>

No other yaml or view files required under your controller folder.

Discussion

0 comments

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