<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0">
  <channel>
    <title>October Tricks Latest</title>
    <link>https://www.wintertricks.com</link>
    <description>Latest Tricks from octobertricks.com</description>
    <atom:link href="" rel="self" type="application/rss+xml"/>
    <item>
      <title>Override the mail content of the users mail</title>
      <link>https://www.wintertricks.com/tricks/override-the-mail-content-of-the-users-mail</link>
      <description>Written with AI for additional context
Rebrand vendor plugin mails without touching the plugin
Category: Mail / Events
Works with: Winter CMS 1.1+ (any plugin that sends view-based mails, e.g. Winter.User)
The problem
Plugins like Winter.User send transactional mails (winter.user::mail.restore,...</description>
      <content:encoded><![CDATA[<p>Written with AI for additional context</p>
<h1>Rebrand vendor plugin mails without touching the plugin</h1>
<p><strong>Category:</strong> Mail / Events
<strong>Works with:</strong> Winter CMS 1.1+ (any plugin that sends view-based mails, e.g. Winter.User)</p>
<h2>The problem</h2>
<p>Plugins like <strong>Winter.User</strong> send transactional mails (<code>winter.user::mail.restore</code>, <code>winter.user::mail.activate</code>) using their own bundled templates. They look generic, and you usually want them in your own branding, layout and tone of voice.</p>
<p>The usual options all have downsides:</p>
<ul>
<li><strong>Editing the vendor views</strong> — gone on the next <code>composer update</code>.</li>
<li><strong>Overriding templates in the backend (Settings → Mail templates)</strong> — works, but the content now lives in the database instead of your git repository. No code review, no deploys, no history, and every environment (local, staging, production) has to be kept in sync by hand.</li>
<li><strong>Forking the plugin</strong> — a maintenance burden for what is essentially a cosmetic change.</li>
</ul>
<p>What you actually want: the vendor plugin keeps <em>triggering</em> its mails exactly as it does today, but the <em>content</em> comes from your own git-tracked templates in your own plugin.</p>
<h2>The trick</h2>
<p>Winter's own mail system renders view-based mails through the global <code>mailer.beforeAddContent</code> event — the System module listens to it to resolve and render the template, and Winter.Translate listens to it for localization. Because event listeners run in priority order and returning <code>false</code> halts propagation, you can register your own listener at a <strong>higher priority</strong>, swap the vendor view code for your own, add the content yourself, and return <code>false</code> so the default handlers never run — but <em>only</em> for the mails you map. Everything else falls through untouched.</p>
<p>In your plugin's <code>boot()</code> method:</p>
<pre><code class="language-php">Event::listen('mailer.beforeAddContent', function ($mailer, $message, $view, $data, $raw, $plain) {
    static $map = [
        'winter.user::mail.restore'  =&gt; 'acme.site::mail.restore',
        'winter.user::mail.activate' =&gt; 'acme.site::mail.activate',
    ];

    // Only the two view-based vendor mails we rebrand; leave raw mails and
    // everything else to the default handlers.
    if ($raw !== null || !is_string($view) || !isset($map[$view])) {
        return;
    }

    $code = $map[$view];

    MailManager::instance()-&gt;addContentToMailer($message, $code, $data);

    return false; // branded content added — skip the vendor template
}, 100);</code></pre>
<p>Your own templates (<code>acme.site::mail.restore</code>, …) are registered the normal way via <code>registerMailTemplates()</code> in your Plugin.php and live as <code>.htm</code> files in your plugin — versioned, reviewable, deployable.</p>
<h2>How it works</h2>
<ol>
<li>Winter.User calls <code>Mail::send('winter.user::mail.restore', …)</code> as usual — nothing changes on the vendor side.</li>
<li>The Mailer fires <code>mailer.beforeAddContent</code> before resolving the template content.</li>
<li>Your listener runs <strong>first</strong> (priority 100 beats the default priority 0 of the System/Translate listeners).</li>
<li>For unmapped views or raw mails it returns nothing, so propagation continues and the framework behaves exactly as stock.</li>
<li>For a mapped view it renders <em>your</em> template into the message via <code>MailManager::addContentToMailer()</code> and returns <code>false</code>, halting the event — so the vendor template is never rendered.</li>
</ol>
<h2>Bonus: keep localization</h2>
<p>If you run a multilingual site with Winter.Translate, you also bypass its localization handler — so resolve the locale-suffixed variant yourself before adding content:</p>
<pre><code class="language-php">$locale = !empty($data['_current_locale']) ? $data['_current_locale'] : App::getLocale();

// Prefer a locale-suffixed variant (restore-fr, activate-en, …), else the base.
$localized = EventRegistry::instance()-&gt;getLocalizedView($mailer-&gt;getViewFactory(), $code, $locale);

MailManager::instance()-&gt;addContentToMailer($message, $localized ?: $code, $data);</code></pre>
<p>(<code>EventRegistry</code> here is <code>Winter\Translate\Classes\EventRegistry</code> — the same class Winter.Translate uses internally, so your naming convention for localized templates stays identical to the rest of your site.)</p>
<h2>When to use this</h2>
<ul>
<li>You want vendor transactional mails in your own branding <strong>and</strong> you want those templates in version control rather than in the database.</li>
<li>You're rebranding a <em>subset</em> of mails and want everything else to keep stock behavior.</li>
<li>You can't or don't want to fork/patch the vendor plugin.</li>
</ul>
<h2>When <em>not</em> to use this</h2>
<ul>
<li>If database-managed templates are fine for your workflow, simply overriding the template content in <strong>Settings → Mail templates</strong> is less code.</li>
<li>If you need to change <em>when</em> or <em>to whom</em> a mail is sent (not just its content), look at the plugin's own events instead — this hook only controls content.</li>
</ul>
<h2>Gotchas</h2>
<ul>
<li>Guard against <code>$raw</code> mails and non-string views (Winter also supports <code>['html' =&gt; …, 'text' =&gt; …]</code> view arrays) — the early return in the snippet handles this.</li>
<li>Keep the listener registration in <code>boot()</code>, not <code>register()</code>, so all mail infrastructure is available.</li>
<li>If another plugin also registers a high-priority listener on this event, priorities decide who wins — pick a number consciously</li>
</ul>]]></content:encoded>
    </item>
    <item>
      <title>Make twig macros available across multiple component partials.</title>
      <link>https://www.wintertricks.com/tricks/make-twig-macros-available-across-multiple-component-partials</link>
      <description>In your plugin, create a views/twig folder and add a file named macros.htm in this folder.
In your components partials, use this to make the macros available:
Note: the _context argument passes the variables visible from the calling partial.</description>
      <content:encoded><![CDATA[<p>In your plugin, create a <code>views/twig</code> folder and add a file named <code>macros.htm</code> in this folder.</p>
<pre><code class="language-twig">{% macro myMacro(vars) %}
    {# do something with vars #}
{% endmacro %}</code></pre>
<p>In your components partials, use this to make the macros available:</p>
<pre><code class="language-twig">{% import "author.plugin::twig.macros" as macros %}

{# you can now use macros.myMacro(_context) #}</code></pre>
<p>Note: the <code>_context</code> argument passes the variables visible from the calling partial.</p>]]></content:encoded>
    </item>
    <item>
      <title>Assign parent to belongsTo relation in create context</title>
      <link>https://www.wintertricks.com/tricks/assign-parent-to-belongsto-relation-in-create-context</link>
      <description>Let's say you have a Client model with hasMany relation to an Invoice model and you would like to automatically assign the client relation widget when creating an Invoice for the Client in the create form.
The Invoice model has...</description>
      <content:encoded><![CDATA[<p>Let's say you have a <code>Client</code> model with <code>hasMany</code> relation to an <code>Invoice</code> model and you would like to automatically assign the client relation widget when creating an Invoice for the Client in the create form.</p>
<p>The Invoice model has this relation:</p>
<pre><code class="language-php">$belongsTo = [
    'client' =&gt; [Client::class],
];</code></pre>
<p>The Invoice form <code>fields.yaml</code> has a "client field" like below:</p>
<pre><code class="language-yaml">client:
    type: relation
    label: Client
    emptyOption: -- Select Client --</code></pre>
<p>Add this to your Invoice model:</p>
<pre><code class="language-php">public function __construct(array $attributes = [])
{
    parent::__construct($attributes);

    $this-&gt;bindEvent('model.form.filterFields', function ($formWidget, $fields, $context) {
        $model = $formWidget-&gt;model;
        if ($context === 'create' &amp;&amp; $model) {
            $model-&gt;client = $client = $formWidget-&gt;getController()-&gt;relationObject-&gt;getParent();
            $fields-&gt;client-&gt;value = $client-&gt;id;
        }
    });
}</code></pre>]]></content:encoded>
    </item>
    <item>
      <title>Using Model::observe() to manage Model events</title>
      <link>https://www.wintertricks.com/tricks/using-modelobserve-to-manage-model-events</link>
      <description>Laravel has a nice way of registering an Observer class to manage Model events:
You can monitor all Laravel events: retrieved, creating, created, updating, updated, saving, saved, restoring, restored, replicating, deleting, deleted, forceDeleting, forceDeleted
First, create an Observer class like...</description>
      <content:encoded><![CDATA[<p>Laravel has a nice way of registering an Observer class to manage Model events:</p>
<p>You can monitor all Laravel events: retrieved, creating, created, updating, updated, saving, saved, restoring, restored, replicating, deleting, deleted, forceDeleting, forceDeleted</p>
<p>First, create an Observer class like this:</p>
<pre><code class="language-php">class MyModelObserver
{
    public function created($model) 
    {
        ...
    }
    public function updated($model) 
    {
        ...
    }
    public function deleted($model) 
    {
        ...
    }
}</code></pre>
<p>Then, simply register the Observer class with your model(s) in the <code>boot()</code> method of your plugin:</p>
<pre><code class="language-php">public function boot()
{
    MyModel::observe(MyModelObserver::class);
}</code></pre>
<p>An Observer class may be used by multiple models if needed:</p>
<pre><code class="language-php">public function boot()
{
    MyModel::observe(MyModelObserver::class);
    MyOtherModel::observe(MyModelObserver::class);
}</code></pre>
<p>You can also add multiple Oberver classes to a model:</p>
<pre><code class="language-php">public function boot()
{
    MyModel::observe([Observer1::class, Observer2::class, ...]);
}</code></pre>]]></content:encoded>
    </item>
    <item>
      <title>Has Many Through ... Pivot</title>
      <link>https://www.wintertricks.com/tricks/has-many-through-pivot</link>
      <description>Has Many Through Pivot means: accessing a distant “one to many” relationship though another relationship that uses a Pivot table (even a polymorphic one) to connect.

Imagine a site where: 

users (User model from Winter.user plugin) can belongs to many...</description>
      <content:encoded><![CDATA[<p><em>Has Many Through Pivot</em> means: accessing a distant “one to many” relationship though another relationship that uses a Pivot table (even a polymorphic one) to connect.
</p>
<p>Imagine a site where: </p>
<ul>
<li>users (<code>User</code> model from Winter.user plugin) can belongs to many companies (<code>Company</code> model)</li>
<li>and each <code>Company</code> has many <code>SalePoint</code>
   </li>
</ul>
<p>How we can attach a <code>SalePoint</code> to a <code>User</code>? A <code>CompanyUser</code> pivot model will help us.
It’s basically a Many-To-Many relation. There are many Users, and many Companies.
   </p>
<h3>First step: Make a CompanyUser Pivot</h3>
<p>Doing this allows to access directly to the pivot table information without the need of raw DB calls. You can use Artisan to make it, or just write it down.
  </p>
<pre><code>php artisan create:model Acme.MyPlugin CompanyUserPivot --pivot  --no-migration </code></pre>
<p>     </p>
<pre><code class="language-php">&lt;?php

namespace Acme\MyPlugin\Models;

use Winter\Storm\Database\Pivot;

/**
 * Company-User Pivot Model
 */
class CompanyUserPivot extends Pivot
{
    /**
     * @var string The database table used by the model.
     */
    public $table = 'acme_myplugin_company_user';

    public $belongsTo = [
        'user' =&gt; \Winter\User\Models\User::class,
        'company' =&gt; \Acme\MyPlugin\Models\Company::class,
    ];

    public $hasManyThrough = [
        'salepoints' =&gt; [
            \Acme\MyPlugin\Models\SalePoint::class,
            'through' =&gt; \Acme\MyPlugin\Models\Company::class,
        ]
    ];
}</code></pre>
<h3>Second Step: Company Model</h3>
<p>Here we need to tell the <code>Company</code> model that we will use our newly created <code>CompanyUserPivot</code> model to connect it to the User model.
  </p>
<pre><code class="language-php">// Plugins/Acme/MyPlugin/Models/Company.php

// Add used class
use Winter\User\Models\User;

// Add relationship
public $belongsToMany = [
    'users' =&gt; [
        User::class,
        'table' =&gt; 'acme_myplugin_company_user',
        'pivotModel' =&gt; 'Acme\MyPlugin\Models\CompanyUserPivot',
    ],
];</code></pre>
<h3>Third Step: Define the inverse for the User Model</h3>
<p>As the <code>User</code> model is already defined, we need to extend it to add relations from our plugin's <code>boot()</code> method.
  </p>
<pre><code class="language-php">// Plugins/Acme/MyPlugin/Plugin.php

// Add used class
use Acme\MyPlugin\Models\Company;
use Winter\User\Models\User;

// Extend User relationships
public function boot(): void
{
    User::extend(function ($model) {
        $model-&gt;belongsToMany = array_merge(
            $model-&gt;belongsToMany, [
                'companies' =&gt; [
                    Company::class,
                    'table' =&gt; 'acme_myplugin_company_user',
                    'pivotModel' =&gt; 'Acme\MyPlugin\Models\CompanyUserPivot',
                    'scope' =&gt; 'isActive'
                ],
            ]
        );
    });
}</code></pre>
<h3>Last Step: Add a touch of magic</h3>
<p>Don’t close our <code>Plugin.php</code> model in your editor just yet!
Now we have to tell our <code>User</code> model to access the <code>SalePoint</code> one using a Has Many Through relationship, but not from <code>Company</code> model, but rather our <code>CompanyUserPivot</code> model.
  </p>
<pre><code class="language-php">// Plugins/Acme/MyPlugin/Plugin.php

// Add used class
use Acme\MyPlugin\Models\Company;
use Acme\MyPlugin\Models\SalePoint;
use Winter\User\Models\User;

// Extend User relationships
public function boot(): void
{
    User::extend(function ($model) {
        $model-&gt;belongsToMany = array_merge(
            $model-&gt;belongsToMany, [
                'companies' =&gt; [
                    Company::class,
                    'table' =&gt; 'acme_myplugin_company_user',
                    'pivotModel' =&gt; 'Acme\MyPlugin\Models\CompanyUserPivot',
                    'scope' =&gt; 'isActive'
                ],
            ]
        );
        $model-&gt;hasManyThrough = array_merge(
            $model-&gt;hasManyThrough, [
                'salepoints' =&gt; [
                    SalePoint::class,
                    'through' =&gt; CompanyUserPivot::class,
                    'key' =&gt; 'user_id',
                    'throughKey' =&gt; 'company_id',
                    'otherKey' =&gt; 'id',
                    'secondOtherKey' =&gt; 'company_id',
                ]
            ]
        );
    });
}</code></pre>
<p>
With that, you can access to the "SalePoints" from the <code>User</code> model with no problems at all, no matter how many sale points it may have.
As a bonus, we aren’t creating any new class hard to maintain, only what Winter gives us.</p>]]></content:encoded>
    </item>
    <item>
      <title>Dynamically change the DatePicker formWidget mode.</title>
      <link>https://www.wintertricks.com/tricks/dynamically-change-the-datepicker-formwidget-mode</link>
      <description>If you have datepicker field in your form, as shown below:
And you need to change it dynamically based on the dateMode field for example, do this in your Plugins.php file:</description>
      <content:encoded><![CDATA[<p>If you have <code>datepicker</code> field in your form, as shown below:</p>
<pre><code class="language-yaml">fields:
    startDate:
        label: Start Date
        type: datepicker
        mode: datetime
        dependsOn: mode

    dateMode:
        type: dropdown
        options:
            date:  Date Only Mode
            datetime: Date And Time Mode</code></pre>
<p>And you need to change it dynamically based on the <code>dateMode</code> field for example, do this in your <code>Plugins.php</code> file:</p>
<pre><code class="language-php">public function boot()
{
    YourModel::extend(function ($model) {
        $model-&gt;bindEvent('model.form.filterFields', function ($form, $fields, $context) {
            if (isset($fields-&gt;dateMode)) {
                $mode = $fields-&gt;dateMode-&gt;value;
                $form-&gt;getFormWidget('startDate')-&gt;mode = $mode;
            }
        }); 
    });
}</code></pre>]]></content:encoded>
    </item>
    <item>
      <title>Apply a default sort configuration based on a filter scope value</title>
      <link>https://www.wintertricks.com/tricks/apply-a-default-sort-configuration-based-on-a-filter-scope-value</link>
      <description>Add the following code in your backend controller class to apply a default sort configuration to your list based on the value selected in a given filter scope:</description>
      <content:encoded><![CDATA[<p>Add the following code in your backend controller class to apply a default sort configuration to your list based on the value selected in a given filter scope:</p>
<pre><code class="language-php">    public function listFilterExtendScopes(Filter $filterWidget)
    {
        $getSortConfig = function (Filter $filter) {
            $currentStatus = $filter-&gt;getScopeValue('status') ?? $filter-&gt;scopes['status']['default'];
            $defaultSorts = [
                'upcoming' =&gt; [
                    'column' =&gt; 'start_date',
                    'direction' =&gt; 'asc',
                ],
                'completed' =&gt; [
                    'column' =&gt; 'start_date',
                    'direction' =&gt; 'desc',
                ],
            ];

            return $defaultSorts[$currentStatus];
        };

        // Apply default sort column / direction logic based on the selected status filter
        $this-&gt;listGetWidget()-&gt;defaultSort = $getSortConfig($filterWidget);

        // Apply default sort config when updating the status filter
        $filterWidget-&gt;bindEvent('filter.update', function () use ($filterWidget, $getSortConfig) {
            if (post('scopeName') === 'status') {
                $sort = $getSortConfig($filterWidget);
                $this-&gt;listGetWidget()-&gt;setSort($sort['column'], $sort['direction']);
            }
        }, 1);
    }</code></pre>]]></content:encoded>
    </item>
    <item>
      <title>Field Access control with FilterFields</title>
      <link>https://www.wintertricks.com/tricks/field-access-control-with-filterfields</link>
      <description>Sometimes you may want to control role readonly for fields in a few model. This filterFields function helps to control the field access but updating a $field_permissions variable instead of keep changing the code.</description>
      <content:encoded><![CDATA[<p>Sometimes you may want to control role readonly for fields in a few model. This filterFields function helps to control the field access but updating a $field_permissions variable instead of keep changing the code.</p>
<pre><code>public function filterFields() {
                        $user_roles = \BackendAuth::getUser()-&gt;role()-&gt;pluck('code')-&gt;toArray();

            if(!empty($model-&gt;field_permissions['roles'])) {
                $readonlyroles = array_keys($model-&gt;field_permissions['roles']);

                $user_got_role = array_intersect($readonlyroles, $user_roles);
                if(!empty($user_got_role)) {
                  foreach($user_got_role as $role) {

                        foreach($model-&gt;field_permissions['roles']['readonly'][$role] as $rf) {
                            $fields-&gt;{$rf}-&gt;readOnly = true; 
                        }

                    }

                }

            }
}

public $field_permissions = [
            'roles' =&gt; [
                    'role1' =&gt; [
                        "name","number"
                        ]
            ]

        ]; </code></pre>]]></content:encoded>
    </item>
    <item>
      <title>Vite - compile assets copying the source structure</title>
      <link>https://www.wintertricks.com/tricks/vite-compile-assets-copying-the-source-structure</link>
      <description/>
      <content:encoded><![CDATA[<p>When compiling theme assets with Vite, the assets are all stored in the <code>themes\mytheme\assets\dist</code> folder.</p>
<p>The result folder structure is : </p>
<pre><code>themes/mytheme
├─ assets
│   ├─ dist
│   │   ├─ manifest.json
│   │   ├─ theme-mytheme-xxxxx.css
│   │   └─ theme-mytheme-xxxxx.js
│   ├─ src
│   │   ├─ css
|   │   │   └─ theme-mytheme.css
│   │   └─ js
|   │       └─ theme-mytheme.js</code></pre>
<p>If you want the <code>dist</code> folder to mimic the <code>src</code> one, you can update your <code>vite.confg.mjs</code> file to add the following : </p>
<pre><code class="language-js">build: {
    outDir: 'assets/dist',
    assetsDir: '',
    rollupOptions: {
        output: {
            assetFileNames: ({name}) =&gt; {
                let extType = name.split('.').at(1);
                if (/\.css$/.test(name ?? '')) {
                    extType = 'css';
                }
                if (/\.(gif|jpe?g|png|svg|ico)$/.test(name ?? '')) {
                    extType = 'images';
                }
                if (/.(woff|woff2|eot|ttf)/.test(name ?? '')) {
                    extType = 'fonts';
                }
                return `${extType}/[name]-[hash][extname]`;
            },
            chunkFileNames: 'js/[name]-[hash].js',
            entryFileNames: 'js/[name]-[hash].js',
        },
    },
},
experimental: {
    renderBuiltUrl: function (filename, { hostId, hostType, type }) {
        if (type === 'asset') {
            if (hostType === 'css') {
                return filename.replace(/(?&lt;type&gt;images|fonts)/i, '../$&lt;type&gt;');
            }
        }
    }
},</code></pre>
<p>The result folder structure will become : </p>
<pre><code>themes/mytheme
├─ assets
│   ├─ dist
|   │   ├─ css
│   │   │   └─  theme-mytheme-xxxxx.css
|   │   ├─ js
│   │   │   └─ theme-mytheme-xxxxx.js
│   │   └─  manifest.json
│   ├─ src
│   │   ├─ css
|   │   |   └─ theme-mytheme.css
│   │   ├─ js
|   │   |   └─ theme-mytheme.js</code></pre>]]></content:encoded>
    </item>
    <item>
      <title>Build menu from StaticMenu</title>
      <link>https://www.wintertricks.com/tricks/build-menu-from-staticmenu</link>
      <description>Required plugin winter.page

and with Twig tag you can make menu :
</description>
      <content:encoded><![CDATA[<h3>Required plugin <strong>winter.page</strong></h3>

<pre><code>[staticMenu mainMenu]
code = "menu_principale"
==
{% import _self as nav %}
{% macro render_menu(items) %}
    {% import _self as nav %}

            {% for item in items | filter(item =&gt; not item.viewBag.isHidden) %}
                &lt;li class="{{ item.isActive ? 'current-menu-item' }} 
                           {{ item.isChildActive ? 'current-menu-item' }} 
                           {{ item.viewBag.cssClass }}"&gt;

            {% if item.url %}
                &lt;a href="{{ item.url }}" {{ item.viewBag.isExternal ? 'target="_blank"' }}&gt;
                    {{ item.code ? item.code|_ : item.title }}
                &lt;/a&gt;
            {% else %}
                &lt;a&gt; {{ item.code ? item.code|_ : item.title }} &lt;/a&gt;
            {% endif %}

            {% if item.items %}
                &lt;ul class="sub-menu"&gt;
                    {{ nav.render_menu(item.items) }}
                &lt;/ul&gt;
            {% endif %}
        &lt;/li&gt;
    {% endfor %}
{% endmacro %}</code></pre>
<h3>and with Twig tag you can make menu :</h3>

<pre><code>{% if mainMenu.menuItems %}
    &lt;ul&gt;
        {{ nav.render_menu(mainMenu.menuItems) }}
    &lt;/ul&gt;
{% endif %}</code></pre>]]></content:encoded>
    </item>
    <item>
      <title>AJAX requests in Plugin Settings</title>
      <link>https://www.wintertricks.com/tricks/ajax-requests-in-plugin-settings</link>
      <description>

Create your Settings plugin as usual, but use the url instead of class property at the registerSettings method.


Create a controller: Settings.php:


Create settings folder in controllers folder with update.htm:


Now you can call your Ajax functions.</description>
      <content:encoded><![CDATA[<ol>
<li><a href="https://wintercms.com/docs/v1.2/docs/plugin/settings#settings-link-registration">Create your Settings plugin as usual</a>, but use the url instead of class property at the registerSettings method.</li>
<li>Create a controller: Settings.php:</li>
</ol>
<pre><code>&lt;?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' =&gt; 'Settings',
        'form' =&gt; "$/author/plugin/models/settings/fields.yaml",
        'modelClass' =&gt; 'Author\Plugin\Models\Settings',
        'defaultRedirect' =&gt; '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-&gt;update();
    }

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

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

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

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

    public function onMyFunction()
    {
    }

}</code></pre>
<ol start="3">
<li>Create settings folder in controllers folder with update.htm:</li>
</ol>
<pre><code>&lt;?php Block::put('breadcrumb') ?&gt;
    &lt;ul&gt;
        &lt;li&gt;&lt;?= e($this-&gt;pageTitle) ?&gt;&lt;/li&gt;
    &lt;/ul&gt;
&lt;?php Block::endPut() ?&gt;

&lt;?= Form::open(['class' =&gt; 'layout']) ?&gt;

    &lt;div class="layout-row"&gt;
        &lt;?= $this-&gt;formRender() ?&gt;
    &lt;/div&gt;

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

&lt;?= Form::close() ?&gt;</code></pre>
<p>Now you can call your Ajax functions.</p>]]></content:encoded>
    </item>
    <item>
      <title>Using the ImportExportController with the List behavior (useList: true)</title>
      <link>https://www.wintertricks.com/tricks/using-the-importexportcontroller-with-the-list-behavior-uselist-true</link>
      <description>Here's a few tricks to use the ImportExportController:
Note: In this example, my controller is called Invoices and my model Invoice.
create a seperate list definition to export your records in your controller:
Add this to your controller:
Use this...</description>
      <content:encoded><![CDATA[<p>Here's a few tricks to use the <code>ImportExportController</code>:</p>
<p>Note: In this example, my controller is called <code>Invoices</code> and my model <code>Invoice</code>.</p>
<p>create a seperate list definition to export your records in your controller:</p>
<p>Add this to your controller:</p>
<pre><code class="language-php">public $implement = [
    'Backend.Behaviors.FormController',
    'Backend.Behaviors.ImportExportController',
    'Backend.Behaviors.ListController',
];

public $listConfig = [
    'list' =&gt; 'config_list.yaml', # your default list definition
    'export' =&gt; [
        'list' =&gt; '$/author/plugin/models/invoice/export_columns.yaml',
        'modelClass' =&gt; 'Author\Plugin\Models\Invoice',
    ],
];

public $importExportConfig = 'config_import_export.yaml';</code></pre>
<p>Use this config_import_export.yaml (note the use of <code>raw: true</code>):</p>
<pre><code class="language-yaml">export:
  fileName: invoices_export.csv
  useList:
    raw: true
    definition: export</code></pre>
<p>And add this to your controller's <code>_list_toolbar.php</code>:</p>
<pre><code>&lt;a
    href="&lt;?= Backend::url('author/plugin/invoices/export') ?&gt;"
    class="wn-icon-download"&gt;
    Export
&lt;/a&gt;</code></pre>
<p>You can also modify the query for your export list by adding this method to your controller:</p>
<pre><code class="language-php">public function listExtendQuery($query, $definition)
{
    if ($definition === 'export') {
        return $query-&gt;where('status', 'complete');
    }
}</code></pre>
<p>And modify the records by adding this method to your controller:</p>
<pre><code class="language-php">public function listExtendRecords($records, $definition = null)
{
    if ($definition === 'export') {
        foreach ($records as $record) {
            ...
        }
    }
}</code></pre>]]></content:encoded>
    </item>
    <item>
      <title>Extending an existing formwidget.</title>
      <link>https://www.wintertricks.com/tricks/extending-an-existing-formwidget</link>
      <description>And you need to register the new formwidget:</description>
      <content:encoded><![CDATA[<pre><code class="language-php">&lt;?php namespace StudioAzura\Foundation\FormWidgets;

use Backend\FormWidgets\RichEditor;

class RichEditorPlus extends RichEditor
{
    protected $defaultAlias = 'rich-editor-plus';

    public function init()
    {
        // set the parent's viewPath so that its partials can be found.
        $this-&gt;addViewPath('~/modules/backend/formwidgets/richeditor/partials');
        parent::init();
    }

    protected function loadAssets()
    {   
        $savedAssetPath = $this-&gt;assetPath;

        // set the parent's assetPath so that its assets can be found.
        $this-&gt;assetPath = '/modules/backend/formwidgets/richeditor/assets';
        parent::loadAssets();

        // reset our own assetPath
        $this-&gt;assetPath = $savedAssetPath;
        $this-&gt;addJs('js/richeditorplus.js');
    }
}</code></pre>
<p>And you need to register the new formwidget:</p>
<pre><code class="language-php">public function registerFormWidgets()
{   
    return [
        FormWidgets\RichEditorPlus::class =&gt; 'richeditorplus',
    ];
}</code></pre>]]></content:encoded>
    </item>
    <item>
      <title>Show files from within a folder via PHP.</title>
      <link>https://www.wintertricks.com/tricks/show-files-from-within-a-folder-via-php</link>
      <description>On my page i wanted to show a collection of Wallpapers per year, that i collect and constantly update. Until now i did it through the Winter.Blog plugin but found that a bit too heavy for such a small feature....</description>
      <content:encoded><![CDATA[<p>On my page i wanted to show a collection of Wallpapers per year, that i collect and constantly update. Until now i did it through the Winter.Blog plugin but found that a bit too heavy for such a small feature. Apart of that i wanted to automate it more, and this is what i came up with.
<em>Please be informed that i am a scriptkid and not a 100% good developer, so the code below certainly can be optimized, but it might lead you into the right direction.</em></p>
<p><strong>IDEA</strong>
Upload an image to a folder and a WinterCMS page or partial checks said folder and shows the files automatically. Use anyone of the codes within the PHP Code section of a page.</p>
<p><strong>SOLUTION 1 (OLDSCHOOL VANILLA)</strong></p>
<pre><code>function onStart()
{
    /*
    $directory = "./".media_path()."/wallpaper/".date("Y");
    $files2 = scandir( $directory, SCANDIR_SORT_DESCENDING);
    $this['newest_file'] = "/wallpaper/".date("Y")."/".$files2[0];

    $files = scandir($directory);
    $lastModifiedTime = array();
    foreach ($files as $file) {
        if ($file != '.' &amp;&amp; $file != '..') {
            $filepath = $directory . DIRECTORY_SEPARATOR . $file;
            $lastModifiedTime[$file] = filemtime($filepath);
        }
    }
    arsort($lastModifiedTime);
    $wallies = [];
    foreach ($lastModifiedTime as $file =&gt; $mtime) {
        //echo "File: $file - Date Modified: " . date('Y-m-d H:i:s', $mtime);
        array_push($wallies, $file);
    }

    $this['wallies'] = "/wallpaper/".date("Y")."/".$wallies[0];</code></pre>
<p><strong> SOLUTION 2: Via ListFolderContents</strong></p>
<pre><code>    $currYear = date("Y");

    $folder = '/wallpaper/'.$currYear;
    $mediaLib = \System\Classes\MediaLibrary::instance();
    //$files = $mediaLib-&gt;listFolderContents($folder, 'size'); //lastModified

    $files = $mediaLib-&gt;listFolderContents($folder, ['by' =&gt; "modified", 'direction' =&gt; "desc"] ); //lastModified
    $this['mediaFiles'] = $files</code></pre>]]></content:encoded>
    </item>
    <item>
      <title>Create a simple, secure API</title>
      <link>https://www.wintertricks.com/tricks/create-a-simple-secure-api</link>
      <description>

Start with creating a folder in your plugins folder: api


Create Plugin.php with your pluginDetails()


Create routes.php


Createhttp/middleware/Auth.php


Create controllers/Orders.php


Add API_KEY with a good long secret value in your .env file


To test this, set up Postman and send...</description>
      <content:encoded><![CDATA[<ol>
<li>Start with creating a folder in your plugins folder: <code>api</code></li>
<li>Create <code>Plugin.php</code> with your <code>pluginDetails()</code></li>
</ol>
<pre><code>&lt;?php namespace Aic\Api;
use System\Classes\PluginBase;

class Plugin extends PluginBase {

    public function pluginDetails()
    {
        return [
            'name'        =&gt; 'API',
            'description' =&gt; 'API for tracking application',
            'author'      =&gt; 'Meindert Stijfhals',
            'icon'        =&gt; 'icon-truck'
        ];
    }

}</code></pre>
<ol start="3">
<li>Create <code>routes.php</code></li>
</ol>
<pre><code>&lt;?php

Route::group(['prefix' =&gt; 'api/v1', 'middleware' =&gt; ['\Aic\Api\Http\Middleware\Auth']], function() {
    Route::get('/orders', '\Aic\Api\Controllers\Orders@index');
    Route::put('/orders/{id}', '\Aic\Api\Controllers\Orders@update');
});</code></pre>
<ol start="4">
<li>Create<code>http/middleware/Auth.php</code></li>
</ol>
<pre><code>&lt;?php namespace Aic\Api\Http\Middleware;

use Closure;
use Illuminate\Http\Request;

class Auth
{
    public function handle(Request $request, Closure $next)
    {
        $apiKey = $request-&gt;header('Authorization');

        if ($apiKey !== env('API_KEY')) {
            return response()-&gt;json(['error' =&gt; 'Unauthorized'], 401);
        }

        return $next($request);
    }
}</code></pre>
<ol start="5">
<li>Create <code>controllers/Orders.php</code></li>
</ol>
<pre><code>&lt;?php namespace Aic\Api\Controllers;
use Backend\Classes\Controller;

use Illuminate\Http\Request;
use Aic\Account\Models\Order;

class Orders extends Controller
{
    public function index()
    {
                // do something...
        // return Order::all();
        return response()-&gt;json(['message' =&gt; 'API endpoint accessed successfully']);
    }

    public function update(Request $request, $id)
    {
        // $order = Order::findOrFail($id);
                // do something...
        // $order-&gt;update($request-&gt;all());
        // return $order;
                return response()-&gt;json(['message' =&gt; 'API endpoint accessed successfully']);
    }
}</code></pre>
<ol start="6">
<li>
<p>Add <code>API_KEY</code> with a good long secret value in your <code>.env</code> file</p>
</li>
<li>
<p>To test this, set up Postman and send 'Authorization' in header with your private key.
Make sure your website is using HTTPS</p>
</li>
</ol>]]></content:encoded>
    </item>
    <item>
      <title>Writing dynamic validation rules when saving a model</title>
      <link>https://www.wintertricks.com/tricks/writing-dynamic-validation-rules-when-saving-a-model</link>
      <description/>
      <content:encoded><![CDATA[<pre><code>public function beforeSave()
    {
                $rules = [
                        'amount_picked' =&gt; 'numeric|min:0|max:' . $this-&gt;amount_required
                ];

                    \Validator::make($this-&gt;toArray(), $rules)-&gt;validate();
    }</code></pre>
<pre><code>public function beforeValidate()
    {
                $this-&gt;rules['amount_picked'] = 'numeric|min:0|max:' . $this-&gt;amount_required;
    }</code></pre>]]></content:encoded>
    </item>
    <item>
      <title>How to save belongsTo relation in one form without using relation form widget on create</title>
      <link>https://www.wintertricks.com/tricks/how-to-save-belongsto-relation-in-one-form-without-using-relation-form-widget-on-create</link>
      <description>define your fields in fields.yaml as</description>
      <content:encoded><![CDATA[<pre><code>public function formExtendModel($model)
    {

         if ($this-&gt;action == 'create') {
             $model-&gt;address = new \Company\Plugin\Models\Address();
         }

         return $model;
    }
</code></pre>
<p>define your fields in fields.yaml as</p>
<pre><code>fields:
    address[streetname]:
                        label: Name
            type: text
    address[housenumber]:
                        label: House Number
            type: text
   address[zip]:
                        label: Zip
            type: text</code></pre>]]></content:encoded>
    </item>
    <item>
      <title>How to hide all relation toolbar buttons</title>
      <link>https://www.wintertricks.com/tricks/how-to-hide-all-relation-toolbar-buttons</link>
      <description>To hide all relation buttons, you just need to pass an empty array</description>
      <content:encoded><![CDATA[<p>To hide all relation buttons, you just need to pass an empty array</p>
<pre><code>toolbarButtons: []</code></pre>]]></content:encoded>
    </item>
    <item>
      <title>Dynamically Insert a field in an existing form at a given position.</title>
      <link>https://www.wintertricks.com/tricks/dynamically-insert-a-field-in-an-existing-form-at-a-given-position</link>
      <description>Note: credit to @jaxwilko
You can add the following helper method in your plugin's boot method to make this easier:
The example above would become:</description>
      <content:encoded><![CDATA[<pre><code class="language-php">Event::listen('backend.form.extendFieldsBefore', function ($widget) {
    if (!$widget-&gt;getController() instanceof MyController || !$widget-&gt;model instanceof MyModel {
        return; 
    }
    $position = 4;
    $before = $widget-&gt;fields;
    $after = array_splice($before, $position-1);

    $newFields = [
        'myFirstField' =&gt; [
            'type' =&gt; 'text',
            'label' =&gt; 'My First Field',
        ],
        'mySecondField' =&gt; [
            'type' =&gt; 'switch',
            'label' =&gt; 'My Second Field',
        ],
    ];      
    $widget-&gt;fields = array_merge($before, $newFields, $after);
});</code></pre>
<p>Note: credit to @jaxwilko</p>
<p>You can add the following helper method in your plugin's boot method to make this easier:</p>
<pre><code class="language-php">\Backend\Widgets\Form::extend(function () {
    $this-&gt;addDynamicMethod('insertFieldsAtPosition', function ($fields, $position) {
        $after = array_splice($this-&gt;fields, $position-1);
        $this-&gt;fields = array_merge($this-&gt;fields, $fields, $after);
    }); 
}, true);</code></pre>
<p>The example above would become:</p>
<pre><code class="language-php">Event::listen('backend.form.extendFieldsBefore', function ($widget) {
    if (!$widget-&gt;getController() instanceof MyController || !$widget-&gt;model instanceof MyModel {
            return; 
    }
    $widget-&gt;insertFieldsAtPosition([
        'myFirstField' =&gt; [
            'type' =&gt; 'text',
            'label' =&gt; 'My First Field',
        ],
        'mySecondField' =&gt; [
            'type' =&gt; 'switch',
            'label' =&gt; 'My Second Field',
        ],
    ], position:4); 
});</code></pre>]]></content:encoded>
    </item>
    <item>
      <title>Extend Froala editor</title>
      <link>https://www.wintertricks.com/tricks/extend-froala-editor</link>
      <description>Example of how to extend the Froala editor</description>
      <content:encoded><![CDATA[<p>Example of how to extend the Froala editor</p>
<pre><code class="language-php">use Backend\Classes\Controller;
public function boot()
{
    // extend richeditor with custom color picker
    Controller::extend(function ($widget) {
        $widget-&gt;addJs('/plugins/aic/globals/assets/js/froala-color-picker.js');
    });
}</code></pre>
<pre><code class="language-javascript">/*
|------------------
| Extend Richeditor
|------------------
 */
+function ($) { "use strict";
    $(document).render(function() {
        if ($.FroalaEditor) {
            $.FroalaEditor.DEFAULTS = $.extend($.FroalaEditor.DEFAULTS, {
                colorsText: [
                    'REMOVE',
                    '#333333',
                    '#848484',
                    '#E0DFDD',
                    '#F8F6F3',
                    '#FFFFFF',
                    '#FF1616',
                    '#FD5E2B',
                    '#FFE836',
                    '#1EBF80',
                    '#2B7FFD',
                    '#EAF3FF',
                    '#E9B4A6'
                ]
            });
        }
    })
}(window.jQuery);</code></pre>]]></content:encoded>
    </item>
    <item>
      <title>How to return download response from an AJAX handler.</title>
      <link>https://www.wintertricks.com/tricks/how-to-return-download-response-from-an-ajax-handler</link>
      <description>It's not possible to return Response::download directly from an AJAX handler.
Instead, you must return a redirect link to a download route pointing to the content you want to make available for download.
e.g. cms page
Create a file called...</description>
      <content:encoded><![CDATA[<p>It's not possible to return Response::download directly from an AJAX handler.</p>
<p>Instead, you must return a redirect link to a download route pointing to the content you want to make available for download.</p>
<p>e.g. cms page</p>
<pre><code>url = /invoices
layout = default
==
function onStart()
{
    $this['invoices'] = Invoice::all();
}

function onDownload()
{
    $invoiceId = post('id');
    return Redirect::to('/download/invoice/' . $invoiceId);
}
==
&lt;div id="invoices"&gt;
  &lt;ul&gt;
  {% for invoice in invoices %}
    &lt;li&gt;&lt;a href="#" data-request="onDownload" data-request-data="{id: invoice.id}"&gt;&lt;/li&gt;
  {% endfor %}
  &lt;/ul&gt;
&lt;/div&gt;</code></pre>
<p>Create a file called <code>routes.php</code> in your plugin's root folder:</p>
<pre><code class="language-php">&lt;?php

Route::get('/downloads/invoice/{id}', function ($id) {
    $invoicePath = storage_path('invoices/' . $id);
    return Response::download($invoicePath, 'invoice.pdf');
});</code></pre>]]></content:encoded>
    </item>
    <item>
      <title>Website theme switcher by URL</title>
      <link>https://www.wintertricks.com/tricks/make-a-simple-page-switcher</link>
      <description>This page, if duplicated across themes, allows you to cycle between them.
It is possible to limit the themes available for this loop (see comment note).  

Take care  :
This affects the whole website (as it override the site config),...</description>
      <content:encoded><![CDATA[<p>This page, if duplicated across themes, allows you to cycle between them.
It is possible to limit the themes available for this loop (see comment note).  </p>
<blockquote>
<p><strong>Take care</strong>  :
This affects the whole website (as it override the site config), not just the current user visiting the page.
If you want a more powerfull solution take a look at : <a href="https://github.com/Hounddd/wn-themeswitcher-plugin">Hounddd.ThemeSwitcher</a> plugin.</p>
</blockquote>
<pre><code class="language-twig">title = "Theme switch"
url = "/switch-theme"
layout = "default"
is_hidden = 0
==
&lt;?php
    function onStart()
    {
        use Cms\Classes\Theme;
        use Redirect;

        $themes = collect(array_pluck(Theme::all(), 'dirName'));
        /**
         * Use the above syntax to limit the availaibles themes
         * to those specified
         */
        /*
        $themes = collect([
            'first-theme-code',
            'other-theme-code',
        ]);
        */

        $currentThemeKey = $themes-&gt;search(Theme::getActiveThemeCode());

        $nextThemeKey = $currentThemeKey +1;
        if ($nextThemeKey &gt; $themes-&gt;count() -1) {
            $nextThemeKey = 0;
        }

        $nextTheme = $themes-&gt;only($nextThemeKey)-&gt;first();
        Theme::setActiveTheme($nextTheme);

        return Redirect::to('/');
    }
?&gt;
==
</code></pre>
<p>If only two themes are defined, the page behaves like a "theme switcher".</p>]]></content:encoded>
    </item>
    <item>
      <title>Lock backend records to prevent updates by different users</title>
      <link>https://www.wintertricks.com/tricks/lock-backend-records-to-prevent-updates-by-different-users</link>
      <description>To prevent concurrent access to record updates from the backend, use the following trick:</description>
      <content:encoded><![CDATA[<p>To prevent concurrent access to record updates from the backend, use the following trick:</p>
<pre><code class="language-php">use BackendAuth;
use Cache;
use Carbon\Carbon;
use Flash;
use Redirect;
use Request;
use Session;

public function boot()
{   
    Event::listen('backend.page.beforeDisplay', function ($controller, $action, $params) {
        if (!$controller-&gt;isClassExtendedWith(\Backend\Behaviors\FormController::class)) {
            return;
        }
        if ($action === 'update') {
            $recordId = $params[0];
            if (! $model = $controller-&gt;formFindModelObject($recordId)) {
                return;
            }
            $controller-&gt;initForm($model);

            $cacheKey = sprintf("%s-%d", str_replace('\\', '-', get_class($model)), $recordId);

            $cacheValue = [
                'ip' =&gt; Request::ip(),
                'token' =&gt; Session::get('_token'),
                'user' =&gt; BackendAuth::getUser()-&gt;login,
                'ts' =&gt; Carbon::now()-&gt;timestamp,
            ];

            if (!$lock = Cache::get($cacheKey)) {
                // lock the record for an hour
                Cache::put($cacheKey, $cacheValue, 3600);
                if ($lastLock = Session::get('lastLock')) {
                    Cache::forget($lastLock);
                }
                Session::put('lastLock', $cacheKey);
            } elseif ($lock['token'] !== $cacheValue['token']) {
                $ts = (new Carbon(array_get($lock, 'ts')))-&gt;toDateTimeString();
                $user = strtoupper(array_get($lock, 'user'));
                Flash::error("Opening in PREVIEW mode, user {$user} is updating the record.");
                return Redirect::back();
            }
        } else if ($cacheKey = Session::pull('lastLock')) {
            // unlock record for any other backend page access
            Cache::forget($cacheKey);
        }
    });
}</code></pre>]]></content:encoded>
    </item>
    <item>
      <title>List filter with 3 states</title>
      <link>https://www.wintertricks.com/tricks/list-filter-with-3-states</link>
      <description>If you need to filter a list with 3 states, you can use the "switch" filter type as below:
In your model, add this scope method:</description>
      <content:encoded><![CDATA[<p>If you need to filter a list with 3 states, you can use the "switch" filter type as below:</p>
<pre><code class="language-yaml">monthFilter:
  label: Previous / Current Month
  type: switch
  default: 0
  scope: currentOrPreviousMonth</code></pre>
<p>In your model, add this scope method:</p>
<pre><code class="language-php">public function scopeCurrentOrPreviousMonth($query, $state)
{
    return match ($state) {
            // unfiltered query
        "0" =&gt; $query,
                // filter for state 1
        "1" =&gt; $query-&gt;previousMonth(),
                // filter for state 2
        "2" =&gt; $query-&gt;currentMonth(),
    };  
}</code></pre>]]></content:encoded>
    </item>
    <item>
      <title>Using morphMap to migrate morph-type relations to another model</title>
      <link>https://www.wintertricks.com/tricks/using-morphmap-to-migrate-morph-type-relations-to-another-model</link>
      <description>If you need to migrate morph-type relations that store the model name in the DB, morphMap is really good for this.
That will also take care of translated model fields stored in winter_translate_attributes table.
The following morphMap migrates the relations...</description>
      <content:encoded><![CDATA[<p>If you need to migrate morph-type relations that store the model name in the DB, morphMap is really good for this.</p>
<p>That will also take care of translated model fields stored in winter_translate_attributes table.</p>
<p>The following morphMap migrates the relations from Lovata.Shopaholic plugin to OFFLINE.Mall plugin:</p>
<pre><code>use Winter\Storm\Database\Relations\Relation;

public function boot()
{
    Relation::morphMap([
        'Lovata\Shopaholic\Models\Product'  =&gt; 'OFFLINE\Mall\Models\Product',
        'Lovata\Shopaholic\Models\Category' =&gt; 'OFFLINE\Mall\Models\Category',
    ]);
}</code></pre>]]></content:encoded>
    </item>
    <item>
      <title>Translate settings model</title>
      <link>https://www.wintertricks.com/tricks/translate-settings-model</link>
      <description>Your settings model need to implement "Winter.Translate.Behaviors.TranslatableModel"
If you need to keeps original data if lang is missing  : </description>
      <content:encoded><![CDATA[<p>Your settings model need to implement "Winter.Translate.Behaviors.TranslatableModel"</p>
<pre><code>        $settings        = YourSettingsModel::instance();
        $translator     = Translator::instance();
        $original         = $settings-&gt;toArray();
        $translated    = $settings-&gt;getTranslateAttributes($translator-&gt;getLocale()); // Only translated attributes, no data if lang has none</code></pre>
<p>If you need to keeps original data if lang is missing  : </p>
<pre><code>        $settings        = $this-&gt;mergeAssociativeArrays($original, $translated); // keeps original data if lang is missing  

/**
     * Merge two associative arrays recursively, replacing values of the first
     * array with the values of the second array.
     *
     * @param array $array1
     * @param array $array2
     * @return array
     */
    private function mergeAssociativeArrays($array1, $array2) {
        foreach ($array1 as $key =&gt; $value) {
            if (isset($array2[$key]) &amp;&amp; $array2[$key] !== '') {
                if (is_array($value) &amp;&amp; is_array($array2[$key])) {
                    $array1[$key] = self::mergeAssociativeArrays($array1[$key], $array2[$key]);
                } else {
                    $array1[$key] = $array2[$key];
                }
            }
        }
        return $array1;
    }
</code></pre>]]></content:encoded>
    </item>
    <item>
      <title>Test if partial / component / content file exists before using it.</title>
      <link>https://www.wintertricks.com/tricks/test-if-partial-component-content-file-exists-before-using-it</link>
      <description/>
      <content:encoded><![CDATA[<pre><code class="language-twig">{% if content("myContent") %}
  {% content "myContent" %}
{% else %}
  &lt;other content here&gt;
{% endif %}</code></pre>
<pre><code class="language-twig">{% if partial("myPartial") %}
  {% partial "myPartial" %}
{% else %}
  &lt;other content here&gt;
{% endif %}</code></pre>
<pre><code class="language-twig">{% if component("myComponent") %}
  {% component "myComponent" %}
{% else %}
  &lt;other content here&gt;
{% endif %}</code></pre>]]></content:encoded>
    </item>
    <item>
      <title>Add action buttons to Relation Manage Form</title>
      <link>https://www.wintertricks.com/tricks/add-actions-to-relation-manage-form</link>
      <description>If you want to modify the Relation behavior default Manage Form, just copy the original partial (from modules/backend/behaviors/relationcontroller/partials/_manage_form.php) to your controller's partial folder, prefixing "_relation" to the original partial name.
Modify to your liking. An example to add a "delete"...</description>
      <content:encoded><![CDATA[<p>If you want to modify the Relation behavior default Manage Form, just copy the original partial (from <code>modules/backend/behaviors/relationcontroller/partials/_manage_form.php</code>) to your controller's partial folder, prefixing "_relation" to the original partial name.</p>
<p>Modify to your liking. An example to add a "delete" action is shown below:</p>
<pre><code class="language-php">&lt;button
    type="button"
    class="wn-icon-trash-o btn-icon danger m-l-lg"
    data-request="onRelationButtonDelete"
    data-request-data="checked:[&lt;?= $relationManageId ?&gt;]"
    data-request-confirm="&lt;?= e(trans('backend::lang.relation.delete_confirm')) ?&gt;"
    data-request-success="$(this).trigger('close.oc.popup')"&gt;
&lt;/button&gt;</code></pre>
<p>Starting with Winter v2.1.4, you will be able to override specific partials:</p>
<ul>
<li>_manage_form_footer_create.php</li>
<li>_manage_form_footer_update.php</li>
<li>_manage_pivot_footer.php</li>
<li>_pivot_form_footer.php</li>
</ul>]]></content:encoded>
    </item>
    <item>
      <title>Purging a huge amount of files from public storage.</title>
      <link>https://www.wintertricks.com/tricks/purging-a-huge-amount-of-files-from-public-storage</link>
      <description>If you need to purge a huge amount of files from the storage/app/uploads/public folder, the framework can be used but the process can be really slow (ask Luke Towers).
In such cases, you can generate the full path and purge...</description>
      <content:encoded><![CDATA[<p>If you need to purge a huge amount of files from the <code>storage/app/uploads/public</code> folder, the framework can be used but the process can be really slow (ask Luke Towers).</p>
<p>In such cases, you can generate the full path and purge the files using the technique below:</p>
<ol>
<li>build your file list using tinker or an SQL query (you just need the <code>disk_name</code> column)</li>
<li>dump that list in a file called <code>fileList.txt</code></li>
<li>create the script below</li>
</ol>
<p>bulk_purge.sh</p>
<pre><code>#!/bin/bash

# app root to reach the sorage, uses current directory by default
appRoot=$(pwd)

# relative path to the public uploads
publicPath="storage/app/uploads/public"

while read file; do
    echo "${appRoot}/${publicPath}/${file:0:3}/${file:3:3}/${file:6:3}/$file"
done

find ${appRoot}/${publicPath} -type d -empty | sort -nr | xargs -n1 rmdir </code></pre>
<ol start="4">
<li>run the following command in your terminal:</li>
</ol>
<pre><code>cat fileList.txt | bash bulk_purge.sh</code></pre>]]></content:encoded>
    </item>
    <item>
      <title>Creating a standalone controller for a Settings model.</title>
      <link>https://www.wintertricks.com/tricks/creating-a-standalone-controller-for-a-settings-model</link>
      <description>Create your controller:
plugins/author/plugin/controllers/Settings.php:
And a view for the update action:
plugins/author/plugin/controllers/settings/update.php:
No other yaml or view files required under your controller folder.</description>
      <content:encoded><![CDATA[<p>Create your controller:</p>
<p><code>plugins/author/plugin/controllers/Settings.php</code>:</p>
<pre><code class="language-php">use Backend;
use BackendMenu;
use Winter\Storm\Router\Helper as RouterHelper;

class Settings extends \Backend\Classes\Controller
{
    public $formConfig = [
        'name' =&gt; 'Settings',
        'form' =&gt; "$/author/plugin/models/settings/fields.yaml",
        'modelClass' =&gt; 'Author\Plugin\Models\Settings',
        'defaultRedirect' =&gt; '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-&gt;update();
    }

    public function update($id=null)
    {
        if (is_null($id)) {
            $model = $this-&gt;formCreateModelObject();
            $model = $model-&gt;where('item', $model-&gt;settingsCode)-&gt;first();
            $redirectUrl = RouterHelper::replaceParameters($model, $this-&gt;formGetRedirectUrl('update', $model));
            return Backend::redirect($redirectUrl);
        }                                                              
        return parent::update($id);
    }
}</code></pre>
<p>And a view for the update action:</p>
<p><code>plugins/author/plugin/controllers/settings/update.php</code>:</p>
<pre><code class="language-php">&lt;?php Block::put('breadcrumb') ?&gt;
    &lt;ul&gt;
        &lt;li&gt;&lt;?= e($this-&gt;pageTitle) ?&gt;&lt;/li&gt;
    &lt;/ul&gt;
&lt;?php Block::endPut() ?&gt;

&lt;?= Form::open(['class' =&gt; 'layout']) ?&gt;

    &lt;div class="layout-row"&gt;
        &lt;?= $this-&gt;formRender() ?&gt;
    &lt;/div&gt;

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

&lt;?= Form::close() ?&gt;</code></pre>
<p>No other yaml or view files required under your controller folder.</p>]]></content:encoded>
    </item>
    <item>
      <title>Redirecting a Backend user after login.</title>
      <link>https://www.wintertricks.com/tricks/redirecting-a-backend-user-after-login</link>
      <description/>
      <content:encoded><![CDATA[<pre><code class="language-php">use Backend; 
use Event;
use Session;

use System\Classes\PluginBase;

class Plugin extends PluginBase
{
    public $elevated = true;

    public function boot()
    {
        Event::listen('backend.user.login', function ($user) {
            if ($user-&gt;login === 'myusername') {
                Session::put('url.intended', Backend::url('author/plugin/mycontroller'));
            }
        });
    }
}</code></pre>]]></content:encoded>
    </item>
    <item>
      <title>Formwidget to wrap another formwidget with a prefix/suffix zone.</title>
      <link>https://www.wintertricks.com/tricks/formwidget-to-wrap-another-formwidget-with-a-prefixsuffix-zone</link>
      <description>Create the following folders in your plugin's root folder:
Add this file in the formwidgets folder
Wrapper.php:
Add this file in the formwidgets/wrapper/partials folder
_wrapper.php:
Add this file in the formwidgets/wrapper/assets/css folder
wrapper.css:
Add this to your Plugin.php file:
You...</description>
      <content:encoded><![CDATA[<p>Create the following folders in your plugin's root folder:</p>
<pre><code class="language-shell">formwidgets
formwidgets/wrapper
formwidgets/wrapper/assets
formwidgets/wrapper/assets/css
formwidgets/wrapper/partials</code></pre>
<p>Add this file in the <code>formwidgets</code> folder</p>
<p>Wrapper.php:</p>
<pre><code class="language-php">use Backend\Classes\FormWidgetBase;

class Wrapper extends FormWidgetBase
{   
    protected $defaultAlias = 'wrapper';

    public $prefix;
    public $suffix;
    public $targetType;

    public function init()
    {   
        $this-&gt;fillFromConfig([
            'prefix',
            'suffix',
            'targetType',
        ]);
    }

    protected function loadAssets()
    {   
        $this-&gt;addCss('css/wrapper.css');
    }

    public function render()
    {   
        $this-&gt;prepareVars();
        return $this-&gt;makePartial('wrapper');
    }

    protected function prepareVars()
    {   
        $this-&gt;vars['prefix'] = $this-&gt;prefix;
        $this-&gt;vars['suffix'] = $this-&gt;suffix;

        $this-&gt;vars['fieldContent'] = $this-&gt;getParentForm()-&gt;makePartial( 'field_' . $this-&gt;config-&gt;targetType, [
            'field' =&gt; $this-&gt;formField,
            'formModel' =&gt; $this-&gt;model,
        ]);
    }
}</code></pre>
<p>Add this file in the <code>formwidgets/wrapper/partials</code> folder</p>
<p>_wrapper.php:</p>
<pre><code class="language-php">&lt;div class="wrapper"&gt;
&lt;?php if ($prefix) : ?&gt;
  &lt;span class="prefix"&gt;&lt;?= $prefix ?&gt;&lt;/span&gt;
&lt;?php endif ?&gt;
  &lt;?= $fieldContent ?&gt;
&lt;?php if ($suffix) : ?&gt;
  &lt;span class="suffix"&gt;&lt;?= $suffix ?&gt;&lt;/span&gt;
&lt;?php endif ?&gt;
&lt;/div&gt;</code></pre>
<p>Add this file in the <code>formwidgets/wrapper/assets/css</code> folder</p>
<p>wrapper.css:</p>
<pre><code class="language-css">.wrapper {
    display: inline-flex;
    justify-content: center;
    align-items: center;
}       

.prefix,
.suffix {
    width: fit-content;
    height:38px;
    padding: 0.5em;
    border: 1px solid #DDD;
    background-color: #eee;
    z-index: 1;
}           

.prefix {
    border-right: none;
    border-top-left-radius: 10px;
    border-bottom-left-radius: 10px;
    margin-right: -0.25em;
}

.suffix {
    border-left: none;
    border-top-right-radius: 10px;
    border-bottom-right-radius: 10px;
    margin-left: -0.25em;
}</code></pre>
<p>Add this to your Plugin.php file:</p>
<pre><code class="language-php">    public function registerFormWidgets()
    {
        return [
            FormWidgets\Wrapper::class =&gt; 'wrapper',
        ];
    }</code></pre>
<p>You can now create fields like this:</p>
<pre><code class="language-yaml">fields:
  myWrappedEmailField:
    type: wrapper
    targetType: email
    prefix: MyPrefix
    suffix: MySuffix</code></pre>]]></content:encoded>
    </item>
    <item>
      <title>Prevent keyboard popup on mobile for Datepicker formwidget</title>
      <link>https://www.wintertricks.com/tricks/prevent-keyboard-popup-on-mobile-for-datepicker-formwidget</link>
      <description>On mobile, when the DatePicker formwidget opens, you don't want the keyboard to popup.
In order to prevent this behavior, just add the following attribute to your form field definition:</description>
      <content:encoded><![CDATA[<p>On mobile, when the DatePicker formwidget opens, you don't want the keyboard to popup.</p>
<p>In order to prevent this behavior, just add the following attribute to your form field definition:</p>
<pre><code>date:
    type: datepicker
    attributes:
      inputmode: none</code></pre>]]></content:encoded>
    </item>
    <item>
      <title>Loading a page in a popup</title>
      <link>https://www.wintertricks.com/tricks/loading-a-page-in-a-popup</link>
      <description>The purpose of this trick is to load a page (its content only) in a dialog window.  
We will need three parts : 

an Ajax handler to manage the page loading
a popup partial
some JavaScript to handle the dialog...</description>
      <content:encoded><![CDATA[<p>The purpose of this trick is to load a page (its content only) in a dialog window.  </p>
<p>We will need three parts : </p>
<ul>
<li>an Ajax handler to manage the page loading</li>
<li>a popup partial</li>
<li>some JavaScript to handle the dialog open/close </li>
</ul>
<blockquote>
<p>This tricks use <code>Alpine JS</code> to handle the dialog closing by clicking the cancel button or outside the dialog.
You can easily replace @click attributes by vanilla JavaScript events.</p>
</blockquote>
<h3>Add Ajax handler to your layout</h3>
<p>This handler will load a page of the site whose url will be given with a <code>data-request-data</code> attribute, and the push a partial refresh for the popup content.   </p>
<pre><code class="language-php">function onLoadPopUp()
{
    $pageUrl = post('url');
    $content = '&lt;h1&gt;Nothing to load ...&lt;/h1&gt;';
    $title = 'My Popup';

    if ($pageUrl) {
        $handlerController = new Cms\Classes\Controller;

        $router = new \Cms\Classes\Router(\Cms\Classes\Theme::getActiveTheme());
        $page = $router-&gt;findByUrl($pageUrl);
        $page-&gt;layout = null;

        // if the page loaded is a static page from Winter.Pages plugin 
        // and make use of placeholders and/or customs fields, 
        // then you need an "empty" layout repeating your defintions for thoses.
        // $page-&gt;layout = 'empty';

        $content = $handlerController-&gt;runPage($page, false);
        $title = $page-&gt;meta_title ?: $page-&gt;title;
    }

    $this['popupTitle'] = $title;
    $this['popupContent'] = $content;

    return [
        '#dialogContent' =&gt; $this-&gt;renderPartial('popup/_content')
    ];
}</code></pre>
<h3>Add popup's partials</h3>
<p>The two partials defining the popup and its content.</p>
<pre><code>? themes
 ┗ ? yourtheme
   ┗ ? partials
     ┗ ? popup
       ┃ ? _content.htm
       ┗ ? default.htm</code></pre>
<p>1 - <strong>partials/popup/default.htm file :</strong></p>
<pre><code class="language-twig">&lt;dialog id="dialog"&gt;
    &lt;div class="dialog--container" id="dialogContent" @click.outside="closeDialog()"&gt;
    &lt;/div&gt;
&lt;/dialog&gt;</code></pre>
<p>2 - <strong>partials/popup/_content.htm file :</strong></p>
<pre><code class="language-twig">&lt;div class="dialog--headerbar"&gt;
    &lt;span class="dialog--title"&gt;{{ popupTitle }}&lt;/span&gt;
    &lt;button class="btn--cancel" @click="closeDialog()" type="reset" aria-label="Cancel"&gt;
        Cancel
    &lt;/button&gt;
&lt;/div&gt;
&lt;div class="dialog--content"&gt;
    {{ popupContent | raw }}
&lt;/div&gt;</code></pre>
<p>3 - <strong>In your layout, add :</strong> </p>
<pre><code class="language-php">{% partial 'popup/default' %}</code></pre>
<h3>Add some Javascript to show/hide the dialog popup in your theme's asset</h3>
<p>These functions are intended to manage the display of an HTML <code>&lt;dialog&gt;</code> element.  </p>
<pre><code class="language-js">window.openDialog = () =&gt; {
    document.querySelector('#dialog').showModal()
}
window.closeDialog = () =&gt; {
    document.querySelector('#dialog[open]').close()
}</code></pre>
<h3>Add the Ajax handler trigger</h3>
<p>On a link or a button, allows the triggering of the Ajax handler and the opening of the dialog.
In this example the page with the url <code>/thepageurl</code> will be loaded, it must be accessible to the site visitors.  </p>
<pre><code class="language-twig">&lt;a class="..."
    data-request="onLoadPopUp"
    data-request-data="url: '/thepageurl'"
    data-request-success="openDialog()"
&gt;Link text&lt;/a&gt;</code></pre>]]></content:encoded>
    </item>
    <item>
      <title>Wizard style backend form tabs</title>
      <link>https://www.wintertricks.com/tricks/wizard-style-backend-form-tabs</link>
      <description/>
      <content:encoded><![CDATA[<p>This trick turns your backend form tabs into a simple wizard with prev/next buttons.</p>
<ol>
<li>Add some custom JS to your form controllers create method:</li>
</ol>
<pre><code class="language-php">public function create()
{
    $this-&gt;addJs('$/[my-plugin-namespace]/[my-plugin-name]/assets/js/formWizard.js');
    return parent::create();
}</code></pre>
<ol start="2">
<li>Add the formWizard.js under <code>assets/js/formWizard.js</code> in your plugin:</li>
</ol>
<pre><code class="language-js">(() =&gt; {
  /** 
     * returns first parent element matching a selector
     * @param {Element} el
     * @param {String} selector
     * @returns {Element|null}
     * /
  function querySelectorParent(el, selector) {
    if (!el.parentElement &amp;&amp; !el.parentElement.parentElement) {
      return null;
    }
    const match = Array.from(el.parentElement.parentElement.querySelectorAll(selector))
    .filter((parent) =&gt; {
      return parent == el.parentElement;
    })[0] || null;
    if (!match) {
      return querySelectorParent(el.parentElement, selector);
    } else {
      return match;
    }
  }

  window.formWizard = {
    prev: function(btn) {
      const tabPane = querySelectorParent(btn, '.tab-pane');
      const tabNav = querySelectorParent(btn, '.control-tabs');

      if (tabNav &amp;&amp; tabPane) {
        const currentTab = tabNav.querySelector(`a[data-target="#${tabPane.id}"]`);
        const tabs = Array.from(tabNav.querySelectorAll('a[data-toggle="tab"]'))
        .filter((tab) =&gt; {
          return tab.parentElement.style.display !== 'none';
        });
        const index = tabs.indexOf(currentTab);
        tabs[index - 1].click();
      }
    },
    next: function(btn) {
      const tabPane = querySelectorParent(btn, '.tab-pane');
      const tabNav = querySelectorParent(btn, '.control-tabs');

      if (tabNav &amp;&amp; tabPane) {
        const currentTab = tabNav.querySelector(`a[data-target="#${tabPane.id}"]`);
        const tabs = Array.from(tabNav.querySelectorAll('a[data-toggle="tab"]'))
        .filter((tab) =&gt; {
          return tab.parentElement.style.display !== 'none';
        });
        const index = tabs.indexOf(currentTab);
        tabs[index + 1].click();
      }
    }
  };
})();</code></pre>
<ol start="3">
<li>Create a partial for the prev next buttons that should be present in each step under <code>partials/form/_form_wizard_prev_next.php</code> in your plugin:</li>
</ol>
<pre><code class="language-php">&lt;button
    type="button"
    onclick="formWizard.prev(this); return false;"
    class="btn btn-default"
&gt;
    Back
&lt;/button&gt;

&lt;button
    type="button"
    onclick="formWizard.next(this); return false;"
    class="btn btn-primary pull-right"
&gt;
    Continue
&lt;/button&gt;</code></pre>
<ol start="4">
<li>For the first step we only need a next button. Create a partial under <code>partials/form/_form_wizard_next.php</code> in your plugin:</li>
</ol>
<pre><code class="language-php">&lt;button
    type="button"
    onclick="formWizard.next(this); return false;"
    class="btn btn-primary pull-right"
&gt;
    Continue
&lt;/button&gt;</code></pre>
<ol start="5">
<li>
<p>For the last step we need a prev and save button to finish the wizard. Create a partial under <code>partials/form/_form_wizard_prev_save.php</code> in your plugin:</p>
<pre><code class="language-php">&lt;button
type="button"
onclick="formWizard.prev(this); return false;"
class="btn btn-default"
&gt;
Back
&lt;/button&gt;

&lt;button
type="button"
data-request="onSave"
data-request-data="close:1"
data-hotkey="ctrl+enter, cmd+enter"
data-load-indicator="&lt;?= e(trans('backend::lang.form.saving')) ?&gt;"
class="btn btn-primary"&gt;
&lt;?= e(trans('backend::lang.form.create')) ?&gt;
&lt;/button&gt;</code></pre>
</li>
<li>
<p>Now add those partials to the end of each tab in your form:</p>
</li>
</ol>
<pre><code class="language-yaml">tabs:
    fields:
        someField:
            label: Some Field
            tab: First tab
        _buttons_first_tab:
            type: partial
            path: $/my-plugin-namespace/my-plugin-path/partials/form/_form_wizard_next
            tab: First tab

    someOtherField:
            label: Some Other Field
            tab: Second tab
        _buttons_second_tab:
            type: partial
            path: $/my-plugin-namespace/my-plugin-path/partials/form/_form_wizard_prev_next
            tab: Second tab

    someLastField:
            label: Some Last Field
            tab: Last tab
        _buttons_last_tab:
            type: partial
            path: $/my-plugin-namespace/my-plugin-path/partials/form/_form_wizard_prev_save
            tab: Last tab</code></pre>
<p>And here you have a simple wizard using tabs.</p>]]></content:encoded>
    </item>
    <item>
      <title>Replace all columns for an existing List Controller</title>
      <link>https://www.wintertricks.com/tricks/replace-all-list-columns-in-an-existing-controller</link>
      <description/>
      <content:encoded><![CDATA[<pre><code>YourListController::extend(function ($controller) {
    if (!$controller-&gt;listConfig) {
        $controller-&gt;addDynamicProperty('listConfig', 'config_list.yaml');
    }
    $controller-&gt;listConfig = $controller-&gt;mergeConfig($controller-&gt;listConfig, [
        'list' =&gt; '$/myAuthor/myPlugin/config/new_columns.yaml'
    ]);
});</code></pre>]]></content:encoded>
    </item>
    <item>
      <title>Rewriting the definition of all controller columns when extending a plugin</title>
      <link>https://www.wintertricks.com/tricks/rewriting-the-definition-of-all-controller-columns-when-extending-a-plugin</link>
      <description>In some cases, you may want to add or remove columns from a controller's list when extending a plugin.
If there are many columns, this can be a lot of work, so it may be better to completely rewrite the...</description>
      <content:encoded><![CDATA[<p>In some cases, you may want to add or remove columns from a controller's list when extending a plugin.
If there are many columns, this can be a lot of work, so it may be better to completely rewrite the definition of the columns.</p>
<p>In this case, you can use this snippet in your plugin boot method: </p>
<pre><code class="language-php">YourListController::extend(function ($controller) {
    $controller-&gt;listConfig = $controller-&gt;mergeConfig(
                $controller-&gt;listConfig, 
                [
                    'list' =&gt; '$/myAuthor/myPlugin/config/new_columns.yaml'
                ]
    );
});</code></pre>
<p>⚠ Take care, this can create issues if several plugins modify the controller's list columns definition.</p>]]></content:encoded>
    </item>
    <item>
      <title>Create or merge fields when exporting a model</title>
      <link>https://www.wintertricks.com/tricks/create-or-merge-fields-when-exporting-a-model</link>
      <description>Hi,
If you want to merge fields on export you can do the following:


Change your models/ModelExport.php


Add the fields to your models/yourmodelexport/columns.yaml

</description>
      <content:encoded><![CDATA[<p>Hi,</p>
<p>If you want to merge fields on export you can do the following:</p>
<ol>
<li>
<p>Change your models/ModelExport.php</p>
<pre><code>
class YourmodelExport extends ExportModel
{

public $table = 'your_table';

protected $appends = [
    'full_name'
];

public function exportData($columns, $sessionKey = null)
{
    $result = self::make()
        -&gt;get()
        -&gt;toArray();

    return $result;
}

public function getFullNameAttribute()
{
    return $this-&gt;firstname . ' ' . $this-&gt;lastname;
}</code></pre>
</li>
</ol>
<p>}</p>
<pre><code>
2. Add the fields to your models/yourmodelexport/columns.yaml</code></pre>
<p>columns:
...
full_name: Full name</p>
<pre><code></code></pre>]]></content:encoded>
    </item>
    <item>
      <title>Add links on exception-page to open error-line in IDE</title>
      <link>https://www.wintertricks.com/tricks/add-links-on-exception-page-to-open-error-line-in-ide</link>
      <description>Change the following lines in file modules/system/views/exception.php:
Line 21
old:
new:
Line 59
old:
new:
This link is for sublime text but can changed for phpstorm, vcode and other easily.
Now you have to register a custom protocol handler.
On...</description>
      <content:encoded><![CDATA[<p>Change the following lines in file modules/system/views/exception.php:</p>
<p>Line 21
old:</p>
<pre><code>&lt;p&gt;&lt;?=$exception-&gt;getFile()?&gt; &lt;span&gt;line&lt;/span&gt; &lt;?=$exception-&gt;getLine()?&gt;&lt;/p&gt;</code></pre>
<p>new:</p>
<pre><code>&lt;p&gt;
    &lt;a href="subl://open?url=file://&lt;?=$exception-&gt;getFile()?&gt;&amp;line=&lt;?=$exception-&gt;getLine()?&gt;"&gt;
        &lt;?=$exception-&gt;getFile()?&gt; &lt;span&gt;line&lt;/span&gt; &lt;?=$exception-&gt;getLine()?&gt;
    &lt;/a&gt;
&lt;/p&gt;</code></pre>
<p>Line 59
old:</p>
<pre><code>&lt;td&gt;&lt;?=$stackItem-&gt;file?&gt;&lt;/td&gt;</code></pre>
<p>new:</p>
<pre><code>&lt;td&gt;
    &lt;?php
        $file = (dirname(dirname(dirname(dirname(__FILE__)))));
        $file = str_replace('~', $file, $stackItem-&gt;file);
    ?&gt;
    &lt;a href="subl://open?url=file://&lt;?=$file;?&gt;&amp;line=&lt;?=$stackItem-&gt;line;?&gt;"&gt;
        &lt;b&gt;&lt;?=$stackItem-&gt;file?&gt;&lt;/b&gt;
    &lt;/a&gt;
&lt;/td&gt;</code></pre>
<p>This link is for sublime text but can changed for phpstorm, vcode and other easily.
Now you have to register a custom protocol handler.</p>
<p>On linux create a file "subl-url-handler" in a destination of your choice</p>
<pre><code>#!/usr/bin/env bash
arg=${1}

if [[ $arg == *"column"* ]]; then
    pattern=".*file(:\/\/|\=)(.*)&amp;line=(.*)&amp;column=(.*)"
else
    pattern=".*file(:\/\/|\=)(.*)&amp;line=(.*)"
fi

file=$(echo "${arg}" | sed -r "s/${pattern}/\2/")
line=$(echo "${arg}" | sed -r "s/${pattern}/\3/")
column=$(echo "${arg}" | sed -r "s/${pattern}/\4/")

if [ $column == "" ]; then
    DISPLAY=:0.0 /opt/sublime_text/sublime_text $file:$line
else
    DISPLAY=:0.0 /opt/sublime_text/sublime_text $file:$line:$column
fi</code></pre>
<p>then create a file /usr/share/applications/subl-url-handler.desktop</p>
<pre><code>[Desktop Entry]
Version=1.0
Type=Application
Name=subl URL Handler
Comment=Handle URL Scheme subl://open?url=@file&amp;line=@line
Icon=subl
NoDisplay=true
Categories=TextEditor;Utility;
Exec=/path/to/subl-url-handler %u
Terminal=false
MimeType=x-scheme-handler/subl;
X-Desktop-File-Install-Version=0.22</code></pre>
<p>and now run "sudo update-desktop-database" or "update-desktop-database" if you are root</p>
<p>Mac-user can take a look at <a href="https://github.com/asuth/subl-handler">https://github.com/asuth/subl-handler</a></p>
<p>Windows-user can find tipps at <a href="https://github.com/Octarine-Phaneron/custom_protocol">https://github.com/Octarine-Phaneron/custom_protocol</a></p>]]></content:encoded>
    </item>
    <item>
      <title>How to prevent a model from saving using Laravel events</title>
      <link>https://www.wintertricks.com/tricks/how-to-prevent-a-model-from-saving-using-laravel-events</link>
      <description>In the boot() method of your plugin, add this snippet:
or the preferred method:</description>
      <content:encoded><![CDATA[<p>In the <code>boot()</code> method of your plugin, add this snippet:</p>
<pre><code>Event::listen('eloquent.saving: System\Models\RequestLog', function ($model) {
    if (str_ends_with($model-&gt;url, '/bad-url')) {
        return false;
    }   
});</code></pre>
<p>or the preferred method:</p>
<pre><code>System\Models\RequestLog::saving(function ($model) {
    if (str_ends_with($model-&gt;url, '/bad-url')) {
        return false;
    }
}); </code></pre>]]></content:encoded>
    </item>
    <item>
      <title>Send mail to admins</title>
      <link>https://www.wintertricks.com/tricks/send-mail-to-admins</link>
      <description/>
      <content:encoded><![CDATA[<pre><code>$admins = User::whereHas('groups', function($query) {
   $query-&gt;where('code', 'owners');
})-&gt;get();

foreach ($admins as $admin) {
    Mail::sendTo($admin-&gt;email, mailTemplate, $data);
}</code></pre>]]></content:encoded>
    </item>
    <item>
      <title>Determining the WinterCMS version</title>
      <link>https://www.wintertricks.com/tricks/determining-the-wintercms-version</link>
      <description>If you need to determine which major version of WinterCMS your plugin is running on, you can use : </description>
      <content:encoded><![CDATA[<p>If you need to determine which major version of WinterCMS your plugin is running on, you can use : </p>
<pre><code class="language-php">use Illuminate\Foundation\Application as Laravel;

if (version_compare(Laravel::VERSION, '9.0.0', '&gt;=')) {
    // WinterCMS 1.2.x
} else {
    // WinterCMS 1.1.x
}</code></pre>]]></content:encoded>
    </item>
    <item>
      <title>How to pass active locale/lang to mail templates data</title>
      <link>https://www.wintertricks.com/tricks/how-to-pass-active-localelang-to-mail-templates-data</link>
      <description>use Event;
use App;
use System\Classes\MailManager;
...</description>
      <content:encoded><![CDATA[<p>use Event;
use App;
use System\Classes\MailManager;
...</p>
<pre><code>public function boot()
{
                            Event::listen('mailer.beforeAddContent', function ($mailer, $message, $view, $data, $raw, $plain) {

            $data['_current_locale'] = !empty($data['_current_locale']) ? $data['_current_locale'] : App::getLocale();

            if (MailManager::instance()-&gt;addContentToMailer($message, $view, $data, $plain)) {
                // the caller who fired the event is expecting a FALSE response to halt the event
                return false;
            }

        }, 1);
    }</code></pre>]]></content:encoded>
    </item>
    <item>
      <title>Add all pages to a backend dropdown field (CMS pages, StaticPages and other plugins like a blog) with translations</title>
      <link>https://www.wintertricks.com/tricks/add-all-pages-to-a-backend-dropdown-field-cms-pages-staticpages-and-other-plugins-like-a-blog-with-translations</link>
      <description>It might not be perfect for your case and you will have to change a few things, but I'm sure it will help you on the way!


Create a dropdown field. Options you can leave empty (getCtaOptions in YourModel.php) or...</description>
      <content:encoded><![CDATA[<p>It might not be perfect for your case and you will have to change a few things, but I'm sure it will help you on the way!</p>
<ol>
<li>Create a dropdown field. Options you can leave empty (getCtaOptions in YourModel.php) or use a global static method like I did</li>
</ol>
<pre><code>cta:
        label: Link
        type: dropdown
        emptyOption: -- select  a page --
        options: \Aic\Globals\Helpers\FormHelper::getCtaOptions</code></pre>
<ol start="2">
<li>Create your method (static method example)</li>
</ol>
<pre><code>&lt;?php namespace Aic\Globals\Helpers;

use Cms\Classes\Theme;
use Cms\Classes\Page as CmsPage;
use Winter\Pages\Classes\Page as StaticPage;

use Aic\BlogX\Models\Blog as BlogX;
use Aic\BlogY\Models\Blog as BlogY;
use Aic\BlogZ\Models\Blog as BlogZ;

class FormHelper
{

    public static function getCtaOptions($formWidget, $formField) {

        $currentTheme = Theme::getActiveTheme();
        $pages = [];

        foreach (CmsPage::listInTheme($currentTheme, false) as $page) {

            // BlogX
            if ($page-&gt;baseFileName == 'blog-x/article') {
                foreach (BlogX::select('id', 'slug', 'title')-&gt;get() as $post) {
                    $key = 'cms:' . $page-&gt;baseFileName . ':slug:' . $post-&gt;slug . ':Aic\BlogX\Models\Blog:' . $post-&gt;id;
                    $pages[$key] = 'Blog X - ' . $post-&gt;title;
                }
            }

            // Same as BlogX for BlogY, BlogZ, ...
                        // ... else if
                        // ... else if

            // All CMS pages
            else {
                if (strpos($page-&gt;baseFileName, 'category') || strpos($page-&gt;baseFileName, 'tag')) {
                    // don't include pages that contain category or tag (in my case not needed)
                } else {
                    $key = 'cms:' . $page-&gt;baseFileName;
                    $pages[$key] = $page-&gt;title;
                }
            }

        }

        foreach (StaticPage::listInTheme($currentTheme, false) as $page) {
            $key = 'static:' . $page-&gt;baseFileName;
            $pages[$key] = $page-&gt;title;
        }

        // sort the associative array alphabetically
        asort($pages);

        // return the pages
        return $pages;

    }

}</code></pre>
<ol start="3">
<li>
<p>Your dropdown should now be populated with all your pages</p>
</li>
<li>
<p>Now you can render them in the frontend using twig</p>
</li>
</ol>
<pre><code>{% set cta = cta|split(':') %}
{% set type = cta[0] %}
{% set baseFileName = cta[1] %}
{% set property = cta[2] %}
{% set slug = cta[3] %}
{% set model = cta[4] %}
{% set id = cta[5] %}

{% if type == 'cms' %}
        {% if property == 'slug' %}

                {% set translatedSlug = slug|translateSlug(model, id) %}
                {% if translatedSlug %}
                        &lt;a href='{{ baseFileName|page({ slug: translatedSlug }) }}'&gt;Button label&lt;/a&gt;
                {% endif %}

        {% else %}
                &lt;a href='{{ baseFileName|page }}'&gt;Button label&lt;/a&gt;
        {% endif %}
{% else %}
        &lt;a href='{{ baseFileName|staticPage }}'&gt;Button label&lt;/a&gt;
{% endif %}</code></pre>
<ol start="5">
<li>Finally, create the <code>|translateSlug</code> filter in your own Plugin.php. Note that for translations, your plugins need to implement the <a href="https://github.com/wintercms/wn-blog-plugin/blob/d53520138bdf93ad39bd4877df6f62b9e8db3bb1/models/Post.php#L26">translatableModel</a></li>
</ol>
<pre><code>public function registerMarkupTags()
{
        return [
                'filters' =&gt; [
                        'translateSlug' =&gt; [$this, 'translateSlug']
                ]
        ];
}

public function translateSlug($slug, $model, $id)
{
        // cancel if Winter.Translate isn't installed
        if (!class_exists('Winter\Translate\Behaviors\TranslatableModel')) return $slug;

        // return the translated slug. Returns an empty string of none was found.
        return $model::find($id)?-&gt;noFallbackLocale()-&gt;getAttributeTranslated('slug');
}</code></pre>
<p>Special thanks to mjauvin and Romain 'Maz' B</p>]]></content:encoded>
    </item>
    <item>
      <title>Dynamically add list filter when none exist in the original listConfig</title>
      <link>https://www.wintertricks.com/tricks/dynamically-add-list-filter-when-none-exist-in-the-original-listconfig</link>
      <description>When a controller uses the ListController behavior and no filter has been defined in its config_list.yaml, this trick will allow you to dynamically create one.


Note: if a filter already exists, use the extendListFilterScopes() method.
ref. https://wintercms.com/docs/backend/lists#extend-filter-scopes</description>
      <content:encoded><![CDATA[<p>When a controller uses the ListController behavior and no filter has been defined in its config_list.yaml, this trick will allow you to dynamically create one.

</p>
<pre><code>Controllers\MyController::extend(function ($controller) {
    if (!$controller-&gt;listConfig) {
        // controller uses the default value
        $controller-&gt;addDynamicProperty('listConfig', 'config_list.yaml');
    }
    $listConfig = $controller-&gt;makeConfig($controller-&gt;listConfig);
    if (!isset($listConfig-&gt;filter)) {
        // no filter defined in config_list.yaml, let's create one
        $listConfig-&gt;filter = [
            'scopes' =&gt; [
                'myScope' =&gt; [
                    'type' =&gt; 'checkbox',
                    'label' =&gt; 'Apply My Scope', 
                    'default' =&gt; false,
                    'conditions' =&gt; 'mod(id,2)',
                ],
            ],
        ];
    }
    $controller-&gt;listConfig = $listConfig;
});</code></pre>
<p>Note: if a filter already exists, use the <code>extendListFilterScopes()</code> method.
ref. <a href="https://wintercms.com/docs/backend/lists#extend-filter-scopes">https://wintercms.com/docs/backend/lists#extend-filter-scopes</a></p>]]></content:encoded>
    </item>
    <item>
      <title>Add locale field to System\Models\File</title>
      <link>https://www.wintertricks.com/tricks/add-locale-field-to-systemmodelsfile</link>
      <description>In order to be able to attach files for different locales to models, we can extend the System\Models\File Model as shown below. Using an AttachOne or AttachMany relation and adding the "translatable" =&gt; true option to the relation, you could...</description>
      <content:encoded><![CDATA[<p>In order to be able to attach files for different locales to models, we can extend the <code>System\Models\File</code> Model as shown below. Using an AttachOne or AttachMany relation and adding the <code>"translatable" =&gt; true</code> option to the relation, you could then add multiple files and specify their locale using the added field. Use the code below in your Plugin's boot method:</p>
<pre><code>use System\Models\File as FileModel;

...

public function boot()
{
    \Winter\Storm\Database\Model::extend(function ($model) {
        if ($model-&gt;attachOne) {
            foreach ($model-&gt;{'attachOne'} as $relationName =&gt; $options) {
                if ($options[0] === 'System\Models\File' &amp;&amp; isset($options['translatable']) &amp;&amp; !isset($model-&gt;attachMany[$relationName])) {
                    $model-&gt;attachMany = array_merge ($model-&gt;attachMany, [$relationName =&gt; $options]);
                    unset($model-&gt;attachOne[$relationName]);
                }
            }
        }
    });

    \Event::listen('backend.form.extendFields', function ($widget) {
        if ($widget-&gt;model instanceof FileModel) {
            $widget-&gt;addFields([
                'locale' =&gt; [
                    'label'   =&gt; 'Locale',
                    'type'    =&gt; 'dropdown',
                ],
            ]);
        }
    });

    FileModel::extend(function ($model) {
        $model-&gt;bindEvent('model.beforeSave', function () use ($model) {
            if ($model-&gt;locale === 'any') {
                $model-&gt;locale = null;
            }
        });

        $model-&gt;addDynamicMethod('getLocaleOptions', function () {
            $activeLocales = \Winter\Translate\Models\Locale::listEnabled();
            return array_merge(['any' =&gt; 'Any'], $activeLocales);
        });

        $locale = \App::getLocale();
        if (!\App::runningInBackend()) {
            $model::addGlobalScope('localized', function ($builder) use ($locale) {
                $builder-&gt;whereNull('locale')-&gt;orWhere('locale', $locale);
            });
        }
    }); 
}</code></pre>
<p>A global scope is also added to the FileModel in order to only fetch the records with no locale (locale == null) or the currently active locale.</p>]]></content:encoded>
    </item>
    <item>
      <title>Create a custom pagintion for the Winter.Blog Plugin.</title>
      <link>https://www.wintertricks.com/tricks/create-a-custom-pagintion-for-the-winterblog-plugin</link>
      <description>When using the Winter Blog plugin the component also creates you an example pagination with a left arrow together with the word "Last", then ALL PAGES followed by a right arrow and the word "Next".
The problem is that with...</description>
      <content:encoded><![CDATA[<p>When using the Winter Blog plugin the component also creates you an example pagination with a left arrow together with the word "Last", then <strong>ALL PAGES</strong> followed by a right arrow and the word "Next".</p>
<p>The problem is that with many items, the pagination can become very big and depending on how you CSS it, it might break into a second row.</p>
<p>So instead of having a pagination like
<strong>PREVIOUS 1 - 2 - 3 - 4 - 5 - 6 - 7 - 8 - 9 - 10 - 11 - 12 - 13 - 14 - 15 - 16 NEXT</strong></p>
<p>The following code allows you to have something like this:
<strong>PREVIOUS 5 - 6 - 7 - 8 - 9 NEXT</strong></p>
<pre><code>{% if posts.currentPage &lt; posts.lastPage - 4 %}
        {% for page in posts.currentPage..posts.currentPage + 4 %}
                &lt;a href="{{ this.page.baseFileName | page({ (blogPosts.pageParam): page }) }}" class="{{ posts.currentPage == page ? 'active' : null }} item"&gt;{{ page }}&lt;/a&gt;
        {% endfor %}
{% else %}
        {% for page in posts.currentPage..posts.lastPage  %}
        &lt;a href="{{ this.page.baseFileName | page({ (blogPosts.pageParam): page }) }}" class="{{ posts.currentPage == page ? 'active' : null }} item"&gt;{{ page }}&lt;/a&gt;
        {% endfor %}
{% endif %}</code></pre>
<p>On the first and second line the number "4" defines how many items you want to be shown between the <strong>PREVIOUS</strong> and the <strong>NEXT</strong> button.</p>]]></content:encoded>
    </item>
    <item>
      <title>How to modify existing form fields?</title>
      <link>https://www.wintertricks.com/tricks/how-to-modify-existing-form-fields</link>
      <description>Don't forget to check for $form-&gt;isNested in your event handler, otherwise that creates problems with nested form widgets (like repeater and nestedforms)</description>
      <content:encoded><![CDATA[<pre><code>\Event::listen('backend.form.extendFieldsBefore', function($widget) {
            if ($widget-&gt;isNested) {
                return;
            }   

            if ($widget-&gt;getController() instanceof Products &amp;&amp; $widget-&gt;model instanceof Product) {
                $widget-&gt;tabs['fields']['additional_descriptions']['form']['fields'] = [
                    'new' =&gt; [
                        'type' =&gt; 'text',
                        'label' =&gt; 'My New Field',
                    ],  
                    'another' =&gt; [
                        'type' =&gt; 'text',
                        'label' =&gt; 'My Other Field',
                    ],  
                ];      
            }

        });</code></pre>
<p>Don't forget to check for $form-&gt;isNested in your event handler, otherwise that creates problems with nested form widgets (like repeater and nestedforms)</p>
<pre><code>if ($widget-&gt;isNested) {
       return;
}</code></pre>]]></content:encoded>
    </item>
    <item>
      <title>Use a rich editor form widget as the Winter.Blog post editor</title>
      <link>https://www.wintertricks.com/tricks/use-a-rich-editor-form-widget-as-the-winterblog-post-editor</link>
      <description>Use the following Event listener to force the Winter.Blog plugin to always use a richeditor form widget.</description>
      <content:encoded><![CDATA[<p>Use the following Event listener to force the Winter.Blog plugin to always use a <code>richeditor</code> form widget.</p>
<pre><code class="language-php">Event::listen('backend.form.extendFields', function($widget) {
        // Extend only the Blog\Posts controller &amp; Extend only Blog\Post model
        if (!($widget-&gt;getController() instanceof \Winter\Blog\Controllers\Posts
                &amp;&amp; $widget-&gt;model instanceof \Winter\Blog\Models\Post)
        ){  
                return;
        }

        $field = $widget-&gt;getField('content');
        if (class_exists('Winter\Translate\FormWidgets\MLRichEditor')) {
                $field-&gt;config['widget'] = 'Winter\Translate\FormWidgets\MLRichEditor';
        } else {
                $field-&gt;config['widget'] = 'Backend\FormWidgets\RichEditor';
        }
});</code></pre>]]></content:encoded>
    </item>
    <item>
      <title>Access Post upload data from AJAX handler</title>
      <link>https://www.wintertricks.com/tricks/access-post-upload-data-from-ajax-handler</link>
      <description/>
      <content:encoded><![CDATA[<pre><code>    public function onPreview()
    {   
        // using the formController
        $model = $this-&gt;formCreateModelObject();
        $this-&gt;initForm($model);
        $form = $this-&gt;formGetWidget();
        $sessionKey = $form-&gt;getSessionKey();
        $photos = $model-&gt;photos()-&gt;withDeferred($sessionKey)-&gt;get();

        // manually using the Input data
        $model = new Land(Input::get('Land'));
        $sessionKey = Input::get('_session_key');
        $photos = $model-&gt;photos()-&gt;withDeferred($sessionKey)-&gt;get();
    }</code></pre>]]></content:encoded>
    </item>
  </channel>
  <channel>
    <title>October Tricks Popular</title>
    <link>https://www.wintertricks.com</link>
    <description>Popular Tricks from octobertricks.com</description>
    <atom:link href="" rel="self" type="application/rss+xml"/>
    <item>
      <title>How to define global functions in Winter CMS</title>
      <link>https://www.wintertricks.com/tricks/how-to-define-global-functions-in-winter-cms</link>
      <description>I've seen this question asked over and over again, here's how to do this cleanly and easily with Winter...

Just add a file called "init.php" within your plugin's root:
init.php:</description>
      <content:encoded><![CDATA[<p>I've seen this question asked over and over again, here's how to do this cleanly and easily with Winter...</p>

<p>Just add a file called "init.php" within your plugin's root:</p>
<p>init.php:</p>
<pre><code>&lt;?php

if (!function_exists('myGlobalFunction')) {
    function myGlobalFunction()
    {
        return "Hello World!";
    }
}</code></pre>]]></content:encoded>
    </item>
    <item>
      <title>Give your form fields more flexibility</title>
      <link>https://www.wintertricks.com/tricks/give-your-form-fields-more-flexibility</link>
      <description>When defining backend form fields aligments whith the span property, you can set it to storm and add the cssClass property to manage the aligment based on Bootstrap classes.  
The css classes col-xs-12 col-sm-6  col-lg-2 mimic the default left/right behavior...</description>
      <content:encoded><![CDATA[<p>When defining backend form fields aligments whith the <code>span</code> property, you can set it to <code>storm</code> and add the <code>cssClass</code> property to manage the aligment based on Bootstrap classes.  </p>
<pre><code class="language-yaml">services:
    label: 'Services'
    span: right
    type: partial
    path: ...
quantity_default:
    label: 'Default quantity'
    span: storm 
    cssClass: 'col-xs-12 col-sm-6 col-lg-2' 
    type: number
quantity_min:
    label: 'Minimum quantity'
    span: storm 
    cssClass: 'col-xs-12 col-sm-6 col-lg-2' 
    type: number
quantity_max:
    label: 'Maximum quantity'
    span: storm 
    cssClass: 'col-xs-12 col-sm-6 col-lg-2' 
    type: number</code></pre>
<p>The css classes <code>col-xs-12 col-sm-6  col-lg-2</code> mimic the default left/right behavior on  <code>xs</code> and <code>sm</code> screens, but align the 3 fields on an half screen for <code>xl</code> screen width.
You can use up to 12 columns to place your fields !</p>
<p>The css classes availables are <code>col-[screen size]-[col size]</code> : </p>
<ul>
<li>screen size :  <code>xs</code>, <code>sm</code>, <code>md</code> or <code>lg</code></li>
<li>col size : from 1 to 12</li>
</ul>]]></content:encoded>
    </item>
    <item>
      <title>Update a single field from a FormController AJAX method</title>
      <link>https://www.wintertricks.com/tricks/update-a-single-field-from-a-formcontroller-ajax-method</link>
      <description>When using an AJAX handler in your Controller, you can update a single form field as shown below:
Note: if using the Javascript API, don't forget to add the form attribute to your JSON request. (ref. https://wintercms.com/docs/v1.2/docs/ajax/javascript-api)
Tip: if you...</description>
      <content:encoded><![CDATA[<p>When using an AJAX handler in your Controller, you can update a single form field as shown below:</p>
<p>Note: if using the Javascript API, don't forget to add the <code>form</code> attribute to your JSON request. (ref. <a href="https://wintercms.com/docs/v1.2/docs/ajax/javascript-api">https://wintercms.com/docs/v1.2/docs/ajax/javascript-api</a>)</p>
<pre><code class="language-php">public function onYourAjaxHandler($id = null, $context = null)
{
    if (is_null($id)) {
        $model = $this-&gt;formCreateModelObject();
        $model = $this-&gt;formExtendModel($model) ?: $model;
    } else {
        $model = $this-&gt;formFindModelObject($id);
    }
    $this-&gt;initForm($model, $context);

    $formWidget = $this-&gt;formGetWidget();
    // use method below instead to work with the RelationController's manage form
    // $formWidget = $this-&gt;relationGetManageWidget();

    $fieldName = 'fieldToUpdate';

    $field = $formWidget-&gt;getField($fieldName);
    $fieldId = sprintf("#%s-group", $field-&gt;getId());
    $field-&gt;value = 'My Dynamic Value';
    $fieldMarkup = $formWidget-&gt;makePartial('field', ['field' =&gt; $field]);

    return [
        $fieldId =&gt; $fieldMarkup,
    ];
}

public function create_onYourAjaxHandler()
{
   return $this-&gt;onYourAjaxHandler(context:"create");
}

public function update_onYourAjaxHandler($id)
{
   return $this-&gt;onYourAjaxHandler($id, context:"update");
}</code></pre>
<p>Tip: if you want to update a repeater field from another custom formwidget on the same form, just use this instead:</p>
<pre><code class="language-php">$controller = $this-&gt;controller;
$controller-&gt;initForm($model);
$fieldMarkup = $controller-&gt;formRenderField('fieldToUpdate', ['useContainer'=&gt;false]);</code></pre>
<p>And return the result shown previously.</p>
<p>You can also refresh a relation field by doing this:</p>
<pre><code class="language-php">return $this-&gt;asExtension('RelationController')-&gt;relationRefresh('my-relation-field');</code></pre>]]></content:encoded>
    </item>
    <item>
      <title>Add AJAX handler to a Settings page without a custom Controller</title>
      <link>https://www.wintertricks.com/tricks/add-ajax-handler-to-a-settings-page-without-custom-controller</link>
      <description>When you are dealing with a plugin's Settings model, you'll probably use the default Settings controller by registering your model like so:
If you need for any reason to add an AJAX handler to this controller, only for your Settings...</description>
      <content:encoded><![CDATA[<p>When you are dealing with a plugin's <code>Settings</code> model, you'll probably use the default <code>Settings</code> controller by registering your model like so:</p>
<pre><code class="language-php">// Plugin.php
public function registerSettings()
{
    return [
        'settings' =&gt; [
            //...
            'class'       =&gt; \AuthorName\PluginName\Models\Settings::class,
        ]
    ];
}</code></pre>
<p>If you need for any reason to add an AJAX handler to this controller, only for your <code>Settings</code> model, you can do it by extending the default controller:</p>
<pre><code class="language-php">// 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()-&gt;current() === Backend\Facades\Backend::url('system/settings')) {
            return;
        }

        // Only for your Settings model
        if ($controller-&gt;formGetWidget()-&gt;model instanceof \AuthorName\PluginName\Models\Settings) {
            $controller-&gt;addDynamicMethod('onAjaxHandlerName', static function () use ($controller) {
                // Do whatever you want here
            });
        }
    });
}</code></pre>
<p>You can then call this AJAX handler from a partial form field.</p>
<pre><code class="language-yaml"># /authorname/pluginname/models/settings/fields.yaml
fields:
    _ajax_button:
        type: partial
        path: $/authorname/pluginname/models/settings/ajax_button.htm
        span: left</code></pre>
<pre><code class="language-html">&lt;!-- /authorname/pluginname/models/settings/ajax_button.htm --&gt;
&lt;button type="button"
        class="btn btn-primary"
        data-request="onAjaxHandlerName"
        data-request-flash
&gt;Call my ajax handler&lt;/button&gt;</code></pre>
<p>This trick can also be used to add basic form's event handler like <code>get*Options</code> on form's refresh field and so on.</p>]]></content:encoded>
    </item>
    <item>
      <title>Control backend access to static pages on a per-page basis</title>
      <link>https://www.wintertricks.com/tricks/control-backend-access-to-static-pages-on-a-per-page-basis</link>
      <description>Sometimes you may want to control the backend access to Winter.Pages static pages on a per-page basis; this trick should give you a starting point to achieve the specific goals of your project.

Note: In its current implementation this is...</description>
      <content:encoded><![CDATA[<p>Sometimes you may want to control the backend access to Winter.Pages static pages on a per-page basis; this trick should give you a starting point to achieve the specific goals of your project.</p>
<blockquote>
<p><strong>Note:</strong> In its current implementation this is not a perfect solution, for instance if you want to give access to a page that's a child of another page then the user will need access to the parent page as well in order for this to work.</p>
</blockquote>
<pre><code class="language-php">&lt;?php 

namespace MyAuthor\MyPlugin;

use App;
use Event;
use BackendAuth;
use ApplicationException;
use Cms\Classes\Theme;
use Backend\Controllers\Users;
use Backend\Models\User;
use Backend\Models\UserPreference;
use Winter\Pages\Classes\Page;
use Winter\Pages\Controllers\Index;

use System\Classes\PluginBase;

class Plugin extends PluginBase
{
    protected $userPreferenceKey = 'myauthor::content.allowed_static_pages';

    public function boot()
    {
        $this-&gt;extendBackendUsersController();
        $this-&gt;extendBackendUserModel();
        $this-&gt;extendWinterPagesPageModel();
        $this-&gt;extendWinterPagesIndexController();
    }

    /**
     * Extends the Backend Users controller to add the field that will be used
     * to specify specific pages that the user has access to.
     *
     * @return void
     */
    protected function extendBackendUsersController()
    {
        // Setup specific page permission functionality
        // @TODO: Indicate parent / child page relationships in page picker
        Users::extendFormFields(function ($form, $model, $context) {
            if (!in_array($context, ['update'])) {
                return;
            }

            $form-&gt;addTabFields([
                'allowed_static_pages' =&gt; [
                    'tab' =&gt; 'backend::lang.user.permissions',
                    'label' =&gt; 'Allowed Static Pages',
                    'comment' =&gt; 'The static pages that the user is allowed to edit',
                    'type' =&gt; 'checkboxlist',
                    'options' =&gt; Page::listInTheme(Theme::getActiveTheme())-&gt;pluck('title', 'fileName')-&gt;toArray(),
                ],
            ]);
        });
    }

    /**
     * Extends the Backend User model to make the content permissions data available as a
     * dynamic attribute that stores the data as a UserPreference record
     *
     * @return void
     */
    protected function extendBackendUserModel()
    {
        User::extend(function ($model) {
            $model-&gt;addDynamicMethod('getAllowedStaticPagesAttribute', function () use ($model) {
                return UserPreference::forUser($model)-&gt;get($this-&gt;userPreferenceKey);
            });

            // TODO: Warning, users can set this value themselves by including it in the POST data sent by an
            // update request on their myaccount page, this is why there is an explicit isSuperuser() check here
            $model-&gt;addDynamicMethod('setAllowedStaticPagesAttribute', function ($value) use ($model) {
                if ($model-&gt;exists &amp;&amp; BackendAuth::user()-&gt;isSuperuser()) {
                    UserPreference::forUser($model)-&gt;set($this-&gt;userPreferenceKey, $value);
                }
            });
        });
    }

    /**
     * Extends the Winter.Pages Page model to prevent users from deleting or persisting changes to
     * pages that they don't have access to.
     *
     * @return void
     */
    protected function extendWinterPagesPageModel()
    {
        Page::extend(function ($model) {
            if (!App::runningInBackend()) {
                return;
            }

            $allowedPages = UserPreference::forUser()-&gt;get($this-&gt;userPreferenceKey);
            if (empty($allowedPages)) {
                return;
            }

            $model-&gt;bindEvent('model.beforeDelete', function () {
                throw new ApplicationException("You do not have permission to delete pages.");
            });

            $model-&gt;bindEvent('model.beforeSave', function () use ($model, $allowedPages) {
                if (!$model-&gt;exists) {
                    throw new ApplicationException("You do not have permission to create new pages.");
                }
                if (!in_array($model-&gt;fileName, $allowedPages)) {
                    throw new ApplicationException("You are not permitted to modify {$model-&gt;fileName}");
                }
            });
        });
    }

    /**
     * Extends the Winter.Pages Index controller to only allow pages that the user has
     * access to to be loaded.
     *
     * @return void
     */
    protected function extendWinterPagesIndexController()
    {
        Index::extend(function ($controller) {
            $allowedPages = UserPreference::forUser()-&gt;get($this-&gt;userPreferenceKey);
            if (empty($allowedPages)) {
                return;
            }

            Event::listen('cms.object.listInTheme', function ($object, $list) use ($allowedPages) {
                if (!($object instanceof Page)) {
                    return;
                }

                foreach ($list as $index =&gt; $page) {
                    if (!in_array($page-&gt;fileName, $allowedPages)) {
                        $list-&gt;forget($index);
                    }
                }
            });
        });
    }
}</code></pre>]]></content:encoded>
    </item>
    <item>
      <title>How to switch to Winter CMS</title>
      <link>https://www.wintertricks.com/tricks/how-to-switch-to-winter-cms</link>
      <description>Please refer to this blog post:
https://wintercms.com/blog/post/how-start-using-winter-cms</description>
      <content:encoded><![CDATA[<p>Please refer to this blog post:</p>
<p><a href="https://wintercms.com/blog/post/how-start-using-winter-cms">https://wintercms.com/blog/post/how-start-using-winter-cms</a></p>]]></content:encoded>
    </item>
    <item>
      <title>Create a re-usable custom list column type with assets and partials</title>
      <link>https://www.wintertricks.com/tricks/create-a-re-usable-custom-list-column-type-with-assets-and-partials</link>
      <description/>
      <content:encoded><![CDATA[<p>While the Winter docs do have information on creating a <a href="https://wintercms.com/docs/backend/lists#custom-column-types">custom list column type</a>, they unfortunately use direct method callbacks, which can make it tricky to use assets for the column type.</p>
<p>By leveraging a List widget event and following the instructions below, you can create a complex custom list column type that supports asset injection into the controller, as well as partial rendering.</p>
<p>For the purposes of this trick, we are creating a <code>graph</code> list column type within the <code>Acme.Demo</code> plugin.</p>
<h3>/plugins/acme/demo/columntypes/Graph.php</h3>
<pre><code>&lt;?php namespace Acme\Demo\ColumnTypes;

use Event;

class Graph
{
    use \System\Traits\ViewMaker;
    use \System\Traits\AssetMaker;

    /**
     * @var \Backend\Classes\Controller Controller instance
     */
    protected $controller;

    /**
     * @var bool Has the column type been rendered?
     */
    protected $rendered = false;

    /**
     * @var bool Has the CSS been injected?
     */
    protected $addedCss = false;

    /**
     * Constructor.
     */
    public function __construct()
    {
        // Inject CSS into controller, only if the column type is actually used
        Event::listen('backend.list.overrideColumnValue', function ($listWidget) {
            if ($this-&gt;rendered &amp;&amp; !$this-&gt;addedCss) {
                $this-&gt;controller = $listWidget-&gt;getController();
                $this-&gt;addCss(
                    '/plugins/acme/demo/columntypes/graph/assets/css/graph.css',
                    'Acme.Demo'
                );

                // Add any additional CSS/JS assets here as required.

                $this-&gt;addedCss = true;
            }
        });
    }

    /**
     * Renders the "graph" column type.
     * 
     * This is the callback which is registered in `registerListColumnTypes` in the Plugin definition file.
     *
     * @param mixed $value
     * @param \Backend\Classes\ListColumn $column
     * @param \October\Rain\Database\Model $record
     * @return array|string
     */
    public function renderValue($value, $column, $record)
    {
        $this-&gt;rendered = true;

        return $this-&gt;makePartial('graph', [
            // Add params for partial here
        ]);
    }
}</code></pre>
<h3>/plugins/acme/demo/Plugin.php</h3>
<pre><code class="language-php">
// ...

    public function registerListColumnTypes()
    {
        return [
            'graph' =&gt; [
                new \Acme\Demo\ColumnTypes\Graph,
                'renderValue',
            ],
        ];
    }

// ...</code></pre>
<p>You can now create the following partials and assets:</p>
<ul>
<li><code>/plugins/acme/demo/columntypes/graph/_graph.htm</code> - Contains the HTML content to output for the column.</li>
<li><code>/plugins/acme/demo/columntypes/graph/assets/css/graph.css</code> - Contains the CSS content that will be injected into the controller and added to the <code>&lt;head&gt;</code>.</li>
</ul>
<p>The custom column type will now be available for use in all list widgets under the <code>graph</code> type.</p>
<p>For example:</p>
<pre><code class="language-yaml">columns:
    progress:
            label: Progress
                type: graph</code></pre>]]></content:encoded>
    </item>
    <item>
      <title>Relation popup: move secondary tabs to a tab</title>
      <link>https://www.wintertricks.com/tricks/relation-popup-move-secondary-tabs-to-a-tab</link>
      <description>When you display a relation list and click on it, it opens a popup (if not using recordUrl).
The SecondaryTab fields in your fields.yaml are placed under a label called 'Misc'.
This is the value of  'defaultTab' for SecondaryTabs.
See:...</description>
      <content:encoded><![CDATA[<p>When you display a relation list and click on it, it opens a popup (if not using recordUrl).
The SecondaryTab fields in your fields.yaml are placed under a label called 'Misc'.
This is the value of  '<a href="https://wintercms.com/docs/backend/forms#form-tab-options">defaultTab</a>' for SecondaryTabs.</p>
<p>See:
</p>
<p>The annoying part (in my opinion) is that these fields are not displayed in a tab.
These fields will always be displayed at the bottom of your relation popup.</p>
<p>If you want, you can modify your fields.yaml, allowing you to place these fields in a tab.
It's actually really easy.</p>
<p>1) Create a custom context for your relation popup using 'context: myValue'</p>
<pre><code>myRelation:
    label: myRelation
    view:
        ...
    manage:
        form: ~/plugins/author/plugin/models/model/fields.yaml
        context: relation</code></pre>
<p>2) Now you can use '@relation' in your fields.yaml. Whenever you manage myRelation, it will now have the context 'relation', allowing you to display the fields that you desire. For example:</p>
<pre><code>created_at@relation:
            tab: Misc
            label: Created at
            type: datepicker
            mode: date
            format: d/m/Y
            default: now</code></pre>
<p>This field will only be shown when you are managing myRelation with the context: relation.</p>
<p>3) In SecondaryTabs, you can add @create, @update, @preview, to display the field when NOT in context: relation</p>
<pre><code>secondaryTabs:
    fields:
        created_at:
            label: Created at
            type: datepicker
            mode: date
            format: d/m/Y
            default: now
            context: ['create', 'update', 'preview']</code></pre>
<p><em>created_at</em> will now be displayed in the secondaryTabs fields when in context: Create, Update, Preview.
<em>created_at</em> will now be displayed in the relation popup fields when in context: relatiation.
The only downside is that you have defined <em>created_at</em> twice in your fields.yaml file.</p>]]></content:encoded>
    </item>
    <item>
      <title>Paginator with limited number of pages displayed at once</title>
      <link>https://www.wintertricks.com/tricks/paginator-with-limited-number-of-pages-displayed-at-once</link>
      <description>The default paginator markup provided by most plugins typically will render out a single item for every page present in the paginated collection. The following markup will allow you to hide all pages except for a given buffer zone around...</description>
      <content:encoded><![CDATA[<p>The default paginator markup provided by most plugins typically will render out a single item for every page present in the paginated collection. The following markup will allow you to hide all pages except for a given buffer zone around the current page as well as the first and last pages. Some visual styling included as well.</p>
<pre><code class="language-twig">&lt;style&gt;
    @import url('https://fonts.googleapis.com/css2?family=Poppins:wght@500&amp;display=swap');

    .paginator-container {
        font-family: 'Poppins', sans-serif;
        text-align: center;
        background: #20b2aa;
        padding: 1em;
    }

    .paginator {
        display: inline-block;
        padding: .75em;
        margin: 0;
        background: white;
        border-radius: 50px;
    }

    .paginator &gt; li {
        display: inline-block;
        border-radius: 50%;
        vertical-align: middle;
    }

    .paginator &gt; li &gt; * {
        display: block;
        border-radius: 50%;
        padding: .5em;
        width: 1.5em;
        height: 1.5em;
        text-align: center;
        line-height: 1.5em;
        text-decoration: none;
        color: #333;
    }

    .paginator &gt; li.prev &gt; *,
    .paginator &gt; li.next &gt; * {
        width: auto;
    }

    .paginator &gt; li.prev &gt; * {
        border-radius: 25px 5px 5px 25px;
    }
    .paginator &gt; li.next &gt; * {
        border-radius: 5px 25px 25px 5px;
    }

    .paginator &gt; li.active &gt; *,
    .paginator &gt; li &gt; *:hover {
        transition: all .4s ease-in;
        background: #20b2aa;
        color: white;
    }
&lt;/style&gt;

{% set paginatedCollection = records %}
{% set pageParam = 'page' %}
{% set beforePage = 3 %}
{% set afterPage = 3 %}
{% set pageTruncateStart = 6 %}
{% set alwaysShow = [1, paginatedCollection.lastPage] %}

{% if paginatedCollection.lastPage &gt; 1 %}
    &lt;div class="paginator-container"&gt;
        &lt;ul class="paginator" role="menubar" aria-label="Pagination"&gt;
            {% if paginatedCollection.currentPage &gt; 1 %}
                &lt;li class="prev"&gt;&lt;a href="{{ this.page.baseFileName | page() }}?{{ pageParam }}={{ paginatedCollection.currentPage - 1 }}"&gt;&lt; Previous&lt;/a&gt;&lt;/li&gt;
            {% endif %}

            {% for page in 1..paginatedCollection.lastPage %}
                {% set distanceFromCurrent = paginatedCollection.currentPage - page %}
                {% if
                    not (page in alwaysShow)
                    and (
                        (
                            paginatedCollection.currentPage &gt; (pageTruncateStart - 1)
                            and distanceFromCurrent &gt; beforePage
                        )
                        or (distanceFromCurrent &lt; (0 - afterPage))
                    )
                %}
                    {% if not displayedDots %}
                        &lt;li&gt;&lt;span&gt;..&lt;/span&gt;&lt;/li&gt;
                    {% endif %}
                    {% set displayedDots = true %}
                {% else %}
                    {% set displayedDots = false %}
                    &lt;li class="{{ paginatedCollection.currentPage == page ? 'active' : '' }}"&gt;
                        &lt;a href="{{ this.page.baseFileName | page() }}?{{ pageParam }}={{ page }}"&gt;{{ page }}&lt;/a&gt;
                    &lt;/li&gt;
                {% endif %}
            {% endfor %}

            {% if paginatedCollection.lastPage &gt; paginatedCollection.currentPage %}
                &lt;li class="next"&gt;&lt;a href="{{ this.page.baseFileName | page() }}?{{ pageParam }}={{ paginatedCollection.currentPage + 1 }}"&gt;Next &gt;&lt;/a&gt;&lt;/li&gt;
            {% endif %}
        &lt;/ul&gt;
    &lt;/div&gt;
{% endif %}</code></pre>]]></content:encoded>
    </item>
    <item>
      <title>Create a simple, secure API</title>
      <link>https://www.wintertricks.com/tricks/create-a-simple-secure-api</link>
      <description>

Start with creating a folder in your plugins folder: api


Create Plugin.php with your pluginDetails()


Create routes.php


Createhttp/middleware/Auth.php


Create controllers/Orders.php


Add API_KEY with a good long secret value in your .env file


To test this, set up Postman and send...</description>
      <content:encoded><![CDATA[<ol>
<li>Start with creating a folder in your plugins folder: <code>api</code></li>
<li>Create <code>Plugin.php</code> with your <code>pluginDetails()</code></li>
</ol>
<pre><code>&lt;?php namespace Aic\Api;
use System\Classes\PluginBase;

class Plugin extends PluginBase {

    public function pluginDetails()
    {
        return [
            'name'        =&gt; 'API',
            'description' =&gt; 'API for tracking application',
            'author'      =&gt; 'Meindert Stijfhals',
            'icon'        =&gt; 'icon-truck'
        ];
    }

}</code></pre>
<ol start="3">
<li>Create <code>routes.php</code></li>
</ol>
<pre><code>&lt;?php

Route::group(['prefix' =&gt; 'api/v1', 'middleware' =&gt; ['\Aic\Api\Http\Middleware\Auth']], function() {
    Route::get('/orders', '\Aic\Api\Controllers\Orders@index');
    Route::put('/orders/{id}', '\Aic\Api\Controllers\Orders@update');
});</code></pre>
<ol start="4">
<li>Create<code>http/middleware/Auth.php</code></li>
</ol>
<pre><code>&lt;?php namespace Aic\Api\Http\Middleware;

use Closure;
use Illuminate\Http\Request;

class Auth
{
    public function handle(Request $request, Closure $next)
    {
        $apiKey = $request-&gt;header('Authorization');

        if ($apiKey !== env('API_KEY')) {
            return response()-&gt;json(['error' =&gt; 'Unauthorized'], 401);
        }

        return $next($request);
    }
}</code></pre>
<ol start="5">
<li>Create <code>controllers/Orders.php</code></li>
</ol>
<pre><code>&lt;?php namespace Aic\Api\Controllers;
use Backend\Classes\Controller;

use Illuminate\Http\Request;
use Aic\Account\Models\Order;

class Orders extends Controller
{
    public function index()
    {
                // do something...
        // return Order::all();
        return response()-&gt;json(['message' =&gt; 'API endpoint accessed successfully']);
    }

    public function update(Request $request, $id)
    {
        // $order = Order::findOrFail($id);
                // do something...
        // $order-&gt;update($request-&gt;all());
        // return $order;
                return response()-&gt;json(['message' =&gt; 'API endpoint accessed successfully']);
    }
}</code></pre>
<ol start="6">
<li>
<p>Add <code>API_KEY</code> with a good long secret value in your <code>.env</code> file</p>
</li>
<li>
<p>To test this, set up Postman and send 'Authorization' in header with your private key.
Make sure your website is using HTTPS</p>
</li>
</ol>]]></content:encoded>
    </item>
    <item>
      <title>Vite - compile assets copying the source structure</title>
      <link>https://www.wintertricks.com/tricks/vite-compile-assets-copying-the-source-structure</link>
      <description/>
      <content:encoded><![CDATA[<p>When compiling theme assets with Vite, the assets are all stored in the <code>themes\mytheme\assets\dist</code> folder.</p>
<p>The result folder structure is : </p>
<pre><code>themes/mytheme
├─ assets
│   ├─ dist
│   │   ├─ manifest.json
│   │   ├─ theme-mytheme-xxxxx.css
│   │   └─ theme-mytheme-xxxxx.js
│   ├─ src
│   │   ├─ css
|   │   │   └─ theme-mytheme.css
│   │   └─ js
|   │       └─ theme-mytheme.js</code></pre>
<p>If you want the <code>dist</code> folder to mimic the <code>src</code> one, you can update your <code>vite.confg.mjs</code> file to add the following : </p>
<pre><code class="language-js">build: {
    outDir: 'assets/dist',
    assetsDir: '',
    rollupOptions: {
        output: {
            assetFileNames: ({name}) =&gt; {
                let extType = name.split('.').at(1);
                if (/\.css$/.test(name ?? '')) {
                    extType = 'css';
                }
                if (/\.(gif|jpe?g|png|svg|ico)$/.test(name ?? '')) {
                    extType = 'images';
                }
                if (/.(woff|woff2|eot|ttf)/.test(name ?? '')) {
                    extType = 'fonts';
                }
                return `${extType}/[name]-[hash][extname]`;
            },
            chunkFileNames: 'js/[name]-[hash].js',
            entryFileNames: 'js/[name]-[hash].js',
        },
    },
},
experimental: {
    renderBuiltUrl: function (filename, { hostId, hostType, type }) {
        if (type === 'asset') {
            if (hostType === 'css') {
                return filename.replace(/(?&lt;type&gt;images|fonts)/i, '../$&lt;type&gt;');
            }
        }
    }
},</code></pre>
<p>The result folder structure will become : </p>
<pre><code>themes/mytheme
├─ assets
│   ├─ dist
|   │   ├─ css
│   │   │   └─  theme-mytheme-xxxxx.css
|   │   ├─ js
│   │   │   └─ theme-mytheme-xxxxx.js
│   │   └─  manifest.json
│   ├─ src
│   │   ├─ css
|   │   |   └─ theme-mytheme.css
│   │   ├─ js
|   │   |   └─ theme-mytheme.js</code></pre>]]></content:encoded>
    </item>
    <item>
      <title>Override external view files locally in your plugin</title>
      <link>https://www.wintertricks.com/tricks/override-a-controllers-view-file-locally-in-your-plugin</link>
      <description>Let's say you want to override a controller's view file (e.g. the Winter.Blog Posts controller):

copy the original view file into your plugin partials directory, under the posts folder.
modify the copied file to your liking
add the following code...</description>
      <content:encoded><![CDATA[<p>Let's say you want to override a controller's <em>view</em> file (e.g. the <code>Winter.Blog</code> Posts controller):</p>
<ul>
<li>copy the original view file into your plugin <code>partials</code> directory, under the <code>posts</code> folder.</li>
<li>modify the copied file to your liking</li>
<li>add the following code to the boot method of your Plugin registration file:</li>
</ul>
<pre><code class="language-php">use Winter\Blog\Controllers\Posts;

public function boot()
{
    Posts::extend(function($controller) {
        list($author, $plugin) = explode('\\', strtolower(get_class()));
        $partials_path = sprintf('$/%s/%s/partials/posts', $author, $plugin);
        $controller-&gt;addViewPath($partials_path);
    });
}</code></pre>
<p>You could also change any of the List widget's view files for a particular controller, adding this <code>relationExtendViewWidget()</code> method to one of your controller:</p>
<pre><code class="language-php">public function relationExtendViewWidget($widget, $field, $model)
{
    $partials_path = '$/author/plugin/partials/lists/';
    $widget-&gt;addViewPath($partials_path);
}</code></pre>
<p>Just copy any of the view files under <code>modules/backend/widgets/lists/partials</code> to your plugins's <code>author/plugin/partials/lists</code> folder.</p>
<p>Of course, replace "author/plugin/" with your particular plugin path.</p>]]></content:encoded>
    </item>
    <item>
      <title>Render an email template programatically</title>
      <link>https://www.wintertricks.com/tricks/render-an-email-template-programatically</link>
      <description>Inspired by the following October trick from OFFLINE: Render an e-mail template in the browser
The following code allows you to programatically render an email template. You can place this within your controller, or as the response to a route,...</description>
      <content:encoded><![CDATA[<p>Inspired by the following October trick from OFFLINE: <a href="https://octobertricks.com/tricks/render-an-e-mail-template-in-the-browser">Render an e-mail template in the browser</a></p>
<p>The following code allows you to programatically render an email template. You can place this within your controller, or as the response to a route, or as a variable for a page or layout template.</p>
<pre><code class="language-php">// Within your use cases
use System\Classes\MailManager;
use System\Models\MailLayout;
use System\Models\MailTemplate;

// The code
$data = [
    'key' =&gt; 'value',
    'foo' =&gt; 'bar',
];

$layout = new MailLayout;
$layout-&gt;fillFromCode('default'); // Change this to use another layout.

$template = new MailTemplate;
$template-&gt;layout = $layout;
$template-&gt;fillFromView('winter.plugin::mail.templates.your-template'); // Use the mail template code here.

$mailContent = MailManager::instance()-&gt;renderTemplate($template, $data);</code></pre>]]></content:encoded>
    </item>
    <item>
      <title>Generate a link to a CMS page</title>
      <link>https://www.wintertricks.com/tricks/generate-a-link-to-a-cms-page</link>
      <description>If you've got the following cms page called blog-post.htm in your theme...
... you can use the following methods to generate a link to it:
In Twig
Pass the name of the cms page file to the page filter. Optionally...</description>
      <content:encoded><![CDATA[<p>If you've got the following cms page called <code>blog-post.htm</code> in your theme...</p>
<pre><code>title = "Blog post"
url = "/blog/:slug"
layout = "default"
is_hidden = 0

[blogPost]
==
{% component 'blogPost' %}</code></pre>
<p>... you can use the following methods to generate a link to it:</p>
<h3>In Twig</h3>
<p>Pass the name of the cms page file to the <code>page</code> filter. Optionally pass along any URL parameters.</p>
<pre><code class="language-twig">{# Example with parameters #}
{{ 'blog-post' | page({slug: 'slug-of-the-post'}) }}

{# Example without parameters #}
{{ 'blog' | page }}

{# Note: If you are linking to a Winter.Pages page, use the staticPage filter #}
{{ 'static-blog' | staticPage }}</code></pre>
<h3>In PHP</h3>
<p>Use the <code>\Cms\Classes\Controller</code> class to generate the URL.</p>
<pre><code class="language-php">// In a page or component context you can access the 
// controller via $this-&gt;controller
$this-&gt;controller-&gt;pageUrl('blog-post', ['slug' =&gt; 'slug-of-the-post']);
// If you don't have access to a controller you can
// easily create a new instance on the fly.
$url = (new \Cms\Classes\Controller)-&gt;pageUrl('blog-post', ['slug' =&gt; 'slug-of-the-post']);
// Or use the Page class helper
\Cms\Classes\Page::url('blog-post', ['slug' =&gt; 'slug-of-the-post'])</code></pre>]]></content:encoded>
    </item>
    <item>
      <title>Relation recordUrl open in new tab</title>
      <link>https://www.wintertricks.com/tricks/relation-recordurl-open-in-new-tab</link>
      <description>If you want the recordUrl to open in a new tab you can do the following:


Add this code to your Controller


Copy modules/backend/widgets/lists/partials/_list_body_row.htm to your author/plugin/partials/list folder and modify to your taste.


Make sure to add an onClick() event...</description>
      <content:encoded><![CDATA[<p>If you want the recordUrl to open in a new tab you can do the following:</p>
<ol>
<li>
<p>Add this code to your Controller</p>
<pre><code>public function relationExtendViewWidget($widget, $field, $model)
{
$partials_path = '$/author/plugin/partials/list/';
$widget-&gt;addViewPath($partials_path);
}</code></pre>
</li>
<li>
<p>Copy <code>modules/backend/widgets/lists/partials/_list_body_row.htm</code> to your <code>author/plugin/partials/list</code> folder and modify to your taste.</p>
</li>
<li>
<p>Make sure to add an onClick() event on the 'a' tag</p>
<pre><code>&lt;a &lt;?= $this-&gt;getRecordOnClick($record) ?&gt; href="&lt;?= $url ?&gt;" onClick="window.open(this.href)"&gt;
&lt;?= $this-&gt;getColumnValue($record, $column) ?&gt;
&lt;/a&gt;</code></pre>
</li>
</ol>]]></content:encoded>
    </item>
    <item>
      <title>Add all pages to a backend dropdown field (CMS pages, StaticPages and other plugins like a blog) with translations</title>
      <link>https://www.wintertricks.com/tricks/add-all-pages-to-a-backend-dropdown-field-cms-pages-staticpages-and-other-plugins-like-a-blog-with-translations</link>
      <description>It might not be perfect for your case and you will have to change a few things, but I'm sure it will help you on the way!


Create a dropdown field. Options you can leave empty (getCtaOptions in YourModel.php) or...</description>
      <content:encoded><![CDATA[<p>It might not be perfect for your case and you will have to change a few things, but I'm sure it will help you on the way!</p>
<ol>
<li>Create a dropdown field. Options you can leave empty (getCtaOptions in YourModel.php) or use a global static method like I did</li>
</ol>
<pre><code>cta:
        label: Link
        type: dropdown
        emptyOption: -- select  a page --
        options: \Aic\Globals\Helpers\FormHelper::getCtaOptions</code></pre>
<ol start="2">
<li>Create your method (static method example)</li>
</ol>
<pre><code>&lt;?php namespace Aic\Globals\Helpers;

use Cms\Classes\Theme;
use Cms\Classes\Page as CmsPage;
use Winter\Pages\Classes\Page as StaticPage;

use Aic\BlogX\Models\Blog as BlogX;
use Aic\BlogY\Models\Blog as BlogY;
use Aic\BlogZ\Models\Blog as BlogZ;

class FormHelper
{

    public static function getCtaOptions($formWidget, $formField) {

        $currentTheme = Theme::getActiveTheme();
        $pages = [];

        foreach (CmsPage::listInTheme($currentTheme, false) as $page) {

            // BlogX
            if ($page-&gt;baseFileName == 'blog-x/article') {
                foreach (BlogX::select('id', 'slug', 'title')-&gt;get() as $post) {
                    $key = 'cms:' . $page-&gt;baseFileName . ':slug:' . $post-&gt;slug . ':Aic\BlogX\Models\Blog:' . $post-&gt;id;
                    $pages[$key] = 'Blog X - ' . $post-&gt;title;
                }
            }

            // Same as BlogX for BlogY, BlogZ, ...
                        // ... else if
                        // ... else if

            // All CMS pages
            else {
                if (strpos($page-&gt;baseFileName, 'category') || strpos($page-&gt;baseFileName, 'tag')) {
                    // don't include pages that contain category or tag (in my case not needed)
                } else {
                    $key = 'cms:' . $page-&gt;baseFileName;
                    $pages[$key] = $page-&gt;title;
                }
            }

        }

        foreach (StaticPage::listInTheme($currentTheme, false) as $page) {
            $key = 'static:' . $page-&gt;baseFileName;
            $pages[$key] = $page-&gt;title;
        }

        // sort the associative array alphabetically
        asort($pages);

        // return the pages
        return $pages;

    }

}</code></pre>
<ol start="3">
<li>
<p>Your dropdown should now be populated with all your pages</p>
</li>
<li>
<p>Now you can render them in the frontend using twig</p>
</li>
</ol>
<pre><code>{% set cta = cta|split(':') %}
{% set type = cta[0] %}
{% set baseFileName = cta[1] %}
{% set property = cta[2] %}
{% set slug = cta[3] %}
{% set model = cta[4] %}
{% set id = cta[5] %}

{% if type == 'cms' %}
        {% if property == 'slug' %}

                {% set translatedSlug = slug|translateSlug(model, id) %}
                {% if translatedSlug %}
                        &lt;a href='{{ baseFileName|page({ slug: translatedSlug }) }}'&gt;Button label&lt;/a&gt;
                {% endif %}

        {% else %}
                &lt;a href='{{ baseFileName|page }}'&gt;Button label&lt;/a&gt;
        {% endif %}
{% else %}
        &lt;a href='{{ baseFileName|staticPage }}'&gt;Button label&lt;/a&gt;
{% endif %}</code></pre>
<ol start="5">
<li>Finally, create the <code>|translateSlug</code> filter in your own Plugin.php. Note that for translations, your plugins need to implement the <a href="https://github.com/wintercms/wn-blog-plugin/blob/d53520138bdf93ad39bd4877df6f62b9e8db3bb1/models/Post.php#L26">translatableModel</a></li>
</ol>
<pre><code>public function registerMarkupTags()
{
        return [
                'filters' =&gt; [
                        'translateSlug' =&gt; [$this, 'translateSlug']
                ]
        ];
}

public function translateSlug($slug, $model, $id)
{
        // cancel if Winter.Translate isn't installed
        if (!class_exists('Winter\Translate\Behaviors\TranslatableModel')) return $slug;

        // return the translated slug. Returns an empty string of none was found.
        return $model::find($id)?-&gt;noFallbackLocale()-&gt;getAttributeTranslated('slug');
}</code></pre>
<p>Special thanks to mjauvin and Romain 'Maz' B</p>]]></content:encoded>
    </item>
    <item>
      <title>Determining the WinterCMS version</title>
      <link>https://www.wintertricks.com/tricks/determining-the-wintercms-version</link>
      <description>If you need to determine which major version of WinterCMS your plugin is running on, you can use : </description>
      <content:encoded><![CDATA[<p>If you need to determine which major version of WinterCMS your plugin is running on, you can use : </p>
<pre><code class="language-php">use Illuminate\Foundation\Application as Laravel;

if (version_compare(Laravel::VERSION, '9.0.0', '&gt;=')) {
    // WinterCMS 1.2.x
} else {
    // WinterCMS 1.1.x
}</code></pre>]]></content:encoded>
    </item>
    <item>
      <title>Using morphMap to migrate morph-type relations to another model</title>
      <link>https://www.wintertricks.com/tricks/using-morphmap-to-migrate-morph-type-relations-to-another-model</link>
      <description>If you need to migrate morph-type relations that store the model name in the DB, morphMap is really good for this.
That will also take care of translated model fields stored in winter_translate_attributes table.
The following morphMap migrates the relations...</description>
      <content:encoded><![CDATA[<p>If you need to migrate morph-type relations that store the model name in the DB, morphMap is really good for this.</p>
<p>That will also take care of translated model fields stored in winter_translate_attributes table.</p>
<p>The following morphMap migrates the relations from Lovata.Shopaholic plugin to OFFLINE.Mall plugin:</p>
<pre><code>use Winter\Storm\Database\Relations\Relation;

public function boot()
{
    Relation::morphMap([
        'Lovata\Shopaholic\Models\Product'  =&gt; 'OFFLINE\Mall\Models\Product',
        'Lovata\Shopaholic\Models\Category' =&gt; 'OFFLINE\Mall\Models\Category',
    ]);
}</code></pre>]]></content:encoded>
    </item>
    <item>
      <title>Create Cms Page from PHP code</title>
      <link>https://www.wintertricks.com/tricks/create-cms-page-from-php-code</link>
      <description>Use this code to programatically create a CMS Page with URL/Title translations:
(Note: to be used with Rainlab.Translate or Winter.Translate plugin)
Use this code to programatically create a CMS Page and attach a component:</description>
      <content:encoded><![CDATA[<p>Use this code to programatically create a CMS Page with URL/Title translations:</p>
<pre><code>    $page = new \Cms\Classes\Page([
        'fileName' =&gt; 'test-page',
        'title' =&gt; 'My Page Title',
        'url' =&gt; '/test-page',
        'layout' =&gt; 'default',
    ]);

    $page-&gt;attributes['viewBag'] = [
            'localeUrl' =&gt; [
                    'fr' =&gt; '/french-URL',
                    'de' =&gt; '/deutch-URL',
            ],
            'localeTitle' =&gt; [
                    'fr' =&gt; 'French Title',
                    'de' =&gt; 'Deutch Title',
            ],
    ];

    $page-&gt;save();</code></pre>
<p>(Note: to be used with <code>Rainlab.Translate</code> or <code>Winter.Translate</code> plugin)</p>
<p>Use this code to programatically create a CMS Page and attach a component:</p>
<pre><code>    $page = new \Cms\Classes\Page([
        'fileName' =&gt; 'test-page',
        'title' =&gt; 'My Page Title',
        'url' =&gt; '/test-page',
        'layout' =&gt; 'default',
    ]);

    $page-&gt;attributes['myComponent'] = [];

    $page-&gt;save();</code></pre>]]></content:encoded>
    </item>
    <item>
      <title>Find all Blog Posts that have a translation in a specific locale</title>
      <link>https://www.wintertricks.com/tricks/find-all-blog-posts-that-have-a-translation-in-a-specific-locale</link>
      <description>If you need to find all Blog Posts that have a translation in a specific locale, use this:
Note: this obviously does not work for the DEFAULT locale
This can easily be integrated with the blogPosts component by adding this...</description>
      <content:encoded><![CDATA[<p>If you need to find all Blog Posts that have a translation in a specific locale, use this:</p>
<pre><code class="language-php">$locale = 'fr';
$posts =  RainLab\Blog\Models\Post::whereHas('translations', function ($query) use ($locale) {
    $query-&gt;where('locale', $locale)-&gt;whereRaw("attribute_data not like '%\"content\":\"\"%'");
})-&gt;get();</code></pre>
<p>Note: this obviously does not work for the DEFAULT locale</p>
<p>This can easily be integrated with the blogPosts component by adding this in your PHP code section:</p>
<pre><code>function onStart()
{
    $locale = $this-&gt;activeLocale;
    if ($locale === 'fr') {
        $untranslatedPostIds = RainLab\Blog\Models\Post::whereDoesntHave('translations', function ($query) use ($locale) { 
            $query-&gt;where('locale', $locale)-&gt;whereRaw("attribute_data not like '%\"content\":\"\"%'");
        })-&gt;lists('id');
        $this-&gt;blogPosts-&gt;setProperty('exceptPost', $untranslatedPostIds);
    }
}</code></pre>]]></content:encoded>
    </item>
    <item>
      <title>Display Next &amp; Previous record buttons in a form</title>
      <link>https://www.wintertricks.com/tricks/display-next-previous-record-buttons-in-a-form</link>
      <description>If you would like to display "Previous" and "Next" buttons in the backend forms of your Winter CMS project you can do the following. This trick assumes you are implementing the FormController and ListController behaviors.

In your Controller, override the...</description>
      <content:encoded><![CDATA[<p>If you would like to display "Previous" and "Next" buttons in the backend forms of your Winter CMS project you can do the following. This trick assumes you are implementing the <code>FormController</code> and <code>ListController</code> behaviors.</p>
<p></p>
<p>In your Controller, override the action method you would like to see the buttons in to include the following:</p>
<pre><code class="language-php">public function preview($id)
    {
        $record = $this-&gt;formFindModelObject($id);

        // Initialize the ListController
        $this-&gt;makeLists();

        // Get the position of the current record within the current list set
        $listQuery = $this-&gt;listGetWidget()-&gt;prepareQuery();
        $totalRecords = $listQuery-&gt;count();
        \DB::statement(\DB::raw('set @row_num=0'));
        $listQuery-&gt;selectRaw('@row_num:= @row_num + 1 as `record_position`');

        $previousId = 0;
        $nextId = 0;
        $currentIndex = null;
                // Note, if you have few records overall but massive sizes per record you can use
                // $listQuery-&gt;cursor() to make one DB query per record instead of loading them all at once
        foreach ($listQuery-&gt;get() as $listRecord) {
            if ($listRecord-&gt;getKey() === $record-&gt;getKey()) {
                $currentIndex = $listRecord-&gt;record_position;
                continue;
            } elseif ($currentIndex) {
                $nextId = $listRecord-&gt;getKey();
                break;
            } else {
                $previousId = $listRecord-&gt;getKey();
            }
        }

        $this-&gt;vars = array_merge($this-&gt;vars, [
            'previousUrl'  =&gt; $previousId ? Backend::url('myauthor/myplugin/mycontroller/preview/' . $previousId) : '',
            'nextUrl'      =&gt; $nextId ? Backend::url('myauthor/myplugin/mycontroller/' . $nextId) : '',
            'currentIndex' =&gt; $currentIndex,
            'totalRecords' =&gt; $totalRecords,
        ]);

        if (!$record-&gt;is_read) {
            $record-&gt;markRead();
        }

        return $this-&gt;asExtension('FormController')-&gt;preview($id);
    }</code></pre>
<p>And then in your action view file (i.e. <code>preview.htm</code>), you can include the following:</p>
<pre><code class="language-php">        &lt;p&gt;
            Record &lt;strong&gt;&lt;?= e($currentIndex); ?&gt;&lt;/strong&gt; of &lt;strong&gt;&lt;?= e($totalRecords); ?&gt;&lt;/strong&gt;. &lt;a href="&lt;?= \Backend::url('myauthor/myplugin/mycontroller/'); ?&gt;"&gt;View all&lt;/a&gt;
        &lt;/p&gt;
        &lt;p&gt;
            &lt;button
                type="button"
                class="btn btn-primary wn-icon-chevron-left"
                onClick="window.location.assign('&lt;?= e($previousUrl); ?&gt;');"
                &lt;?php if (!$previousUrl) : ?&gt;disabled="disabled"&lt;?php endif; ?&gt;
            &gt;Previous&lt;/button&gt;
            &lt;button
                type="button"
                class="btn btn-primary wn-icon-chevron-right"
                onClick="window.location.assign('&lt;?= e($nextUrl); ?&gt;');"
                &lt;?php if (!$nextUrl) : ?&gt;disabled="disabled"&lt;?php endif; ?&gt;
            &gt;Next&lt;/button&gt;
        &lt;/p&gt;</code></pre>
<p>This will take into account the currently applied column orders and list filters present on the index page for your controller.</p>]]></content:encoded>
    </item>
    <item>
      <title>Use Winter Test Plugin as a documentation source</title>
      <link>https://www.wintertricks.com/tricks/winter-test-plugin-documentation-source</link>
      <description>In many cases it is easier learning things by real life examples but by reading abstract documents.
The Winter Test plugin implements a wide variety of coding scenarios, some of them not even mentioned in the official documentation.
If you...</description>
      <content:encoded><![CDATA[<p>In many cases it is easier learning things by real life examples but by reading abstract documents.</p>
<p>The Winter Test plugin implements a wide variety of coding scenarios, some of them not even mentioned in the official documentation.</p>
<p>If you are stuck at some point it is well worth having a look at it!</p>
<pre><code class="language-sh">composer require winter/wn-test-plugin

php artisan winter:up</code></pre>]]></content:encoded>
    </item>
    <item>
      <title>Add a CMS Page reference to your model (Dropdown select)</title>
      <link>https://www.wintertricks.com/tricks/add-a-cms-page-reference-to-your-model-dropdown-select-2</link>
      <description>Sometimes you may want a reference to a specific CMS Page for filtering purposes.
This can be done with just a few lines of code:


add a field to your models database ('cmspage'' in this example)


to fields.yaml add:


to...</description>
      <content:encoded><![CDATA[<p>Sometimes you may want a reference to a specific CMS Page for filtering purposes.</p>
<p>This can be done with just a few lines of code:</p>
<ul>
<li>
<p>add a field to your models database ('cmspage'' in this example)</p>
</li>
<li>
<p>to fields.yaml add:</p>
</li>
</ul>
<pre><code class="language-yaml">
cmspage:
        label: File
        type: dropdown
</code></pre>
<ul>
<li>to YourModel.php add:</li>
</ul>
<pre><code class="language-php">
public function getCmspageOptions($value, $formData) {
        return \Cms\Classes\Page::getNameList();
    }
</code></pre>
<p>This will save the (base-)filename of the selected page which then can be used for filtering purposes.</p>]]></content:encoded>
    </item>
    <item>
      <title>Setting Up Ubuntu to host WinterCMS</title>
      <link>https://www.wintertricks.com/tricks/setting-up-ubuntu-to-host-wintercms</link>
      <description>WinterCMS  can easily be set up on your own server. The following references DigitalOcean, but they can be applied to any Ubuntu server.
Assume you have an Ubuntu instance running (version 20.04 as the the long term supported or 21...</description>
      <content:encoded><![CDATA[<p>WinterCMS  can easily be set up on your own server. The following references <em>DigitalOcean</em>, but they can be applied to any Ubuntu server.</p>
<p>Assume you have an Ubuntu instance running (version 20.04 as the the long term supported or 21 as the bleeding edge), prepare your server according to the following:</p>
<ol>
<li>Read the beginner’s guide that provides a general overview about Ubuntu: <a href="https://www.digitalocean.com/community/conceptual_articles/ubuntu-20-04-beginners-guide">https://www.digitalocean.com/community/conceptual_articles/ubuntu-20-04-beginners-guide</a>.</li>
<li>Create user and review the firewall: <a href="https://www.digitalocean.com/community/tutorials/initial-server-setup-with-ubuntu-20-04">https://www.digitalocean.com/community/tutorials/initial-server-setup-with-ubuntu-20-04</a>.
3.Install web server and PHP: <a href="https://www.digitalocean.com/community/tutorials/how-to-install-linux-nginx-mysql-php-lemp-stack-on-ubuntu-20-04">https://www.digitalocean.com/community/tutorials/how-to-install-linux-nginx-mysql-php-lemp-stack-on-ubuntu-20-04</a>. You may skip <em>MySQL</em>  in case you run WinterCMS with <em>SQLite</em>.</li>
<li>Install composer: ``sudo apt-get install compose```</li>
<li>And finally, WinterCmMS is making use of .htaccess in its installation directory. This might not allowed by the default installation of your web server. Edit <code>/etc/apache2/apache2.con</code> and make sure to define the following: 
<pre><code>&lt;Directory /var/www/&gt;
    Options Indexes FollowSymLinks
    AllowOverride All
    Require all granted
&lt;/Directory&gt;</code></pre>
<p>The key element is to allow override, otherwise the .htaccess in your installation directory will not get executed. Note: The above assumes that you will install your website below /var/www, otherwise reflect accordingly.</p></li>
</ol>]]></content:encoded>
    </item>
    <item>
      <title>Make plugin translation keys available as theme messages for Winter.Translate</title>
      <link>https://www.wintertricks.com/tricks/make-plugin-translation-keys-available-theme-messages-wintertranslate</link>
      <description>This trick is a handy way of distributing Winter.Translate-ready translations with your plugin so that they can be used and overridden by themes.</description>
      <content:encoded><![CDATA[<p>This trick is a handy way of distributing Winter.Translate-ready translations with your plugin so that they can be used and overridden by themes.</p>
<pre><code class="language-php">&lt;?php namespace Acme\Demo;

use Lang;
use Event;
use System\Classes\PluginBase;

class Demo extends PluginBase
{
    public function boot()
    {
        Event::listen('cms.theme.extendConfig', function ($dirName, &amp;$config) {
            $locales = [];
            $results = [];
            $prefix = 'frontend';
            $loader = Lang::getLoader();

            // Get the namespace of the current plugin
            $namespace = str_replace('\\', '.', strtolower(__NAMESPACE__));

            // Scan for available languages under this plugin
            $localeDirectories = glob(plugins_path(str_replace('.', '/', $namespace) . '/lang/*', GLOB_ONLYDIR));
            if (empty($localeDirectories)) {
                return;
            }
            foreach ($localeDirectories as $dir) {
                $locales[] = pathinfo($dir, PATHINFO_BASENAME);
            }

            // Load the messages under the given prefix and prepare them for use
            // as frontend messages
            foreach ($locales as $locale) {
                $translations = $loader-&gt;load($locale, 'lang', $namespace);

                if (!empty($translations[$prefix])) {
                    $results[$locale] = array_dot($translations[$prefix]);
                }
            }

            if (empty($results)) {
                return;
            }

            // Load the plugin's messages into the theme's config, deferring to theme defined messages if present
            foreach ($results as $locale =&gt; $messages) {
                $config['translate'][$locale] = array_merge($messages, @$config['translate'][$locale] ?: []);
            }
        });
    }
}</code></pre>]]></content:encoded>
    </item>
    <item>
      <title>Include SVGs inline in themes</title>
      <link>https://www.wintertricks.com/tricks/include-svgs-inline-themes</link>
      <description>If you would like to include inline SVGs in your theme templates then you can do the following:


Create a partial called include-svg.htm and put the following code in it:


Include your desired SVG like so:

</description>
      <content:encoded><![CDATA[<p>If you would like to include inline SVGs in your theme templates then you can do the following:</p>
<ol>
<li>Create a partial called include-svg.htm and put the following code in it:
<pre><code class="language-php">==
&lt;?php
function onStart() {
$this['svgContents'] = File::get(base_path($this-&gt;file));
}
?&gt;
==
{{ svgContents|raw }}</code></pre></li>
<li>Include your desired SVG like so:
<pre><code class="language-twig">{% partial "include-svg" file="themes/mytheme/assets/images/mysvg.svg" %}</code></pre></li>
</ol>]]></content:encoded>
    </item>
    <item>
      <title>Use a rich editor form widget as the Winter.Blog post editor</title>
      <link>https://www.wintertricks.com/tricks/use-a-rich-editor-form-widget-as-the-winterblog-post-editor</link>
      <description>Use the following Event listener to force the Winter.Blog plugin to always use a richeditor form widget.</description>
      <content:encoded><![CDATA[<p>Use the following Event listener to force the Winter.Blog plugin to always use a <code>richeditor</code> form widget.</p>
<pre><code class="language-php">Event::listen('backend.form.extendFields', function($widget) {
        // Extend only the Blog\Posts controller &amp; Extend only Blog\Post model
        if (!($widget-&gt;getController() instanceof \Winter\Blog\Controllers\Posts
                &amp;&amp; $widget-&gt;model instanceof \Winter\Blog\Models\Post)
        ){  
                return;
        }

        $field = $widget-&gt;getField('content');
        if (class_exists('Winter\Translate\FormWidgets\MLRichEditor')) {
                $field-&gt;config['widget'] = 'Winter\Translate\FormWidgets\MLRichEditor';
        } else {
                $field-&gt;config['widget'] = 'Backend\FormWidgets\RichEditor';
        }
});</code></pre>]]></content:encoded>
    </item>
    <item>
      <title>How to prevent a model from saving using Laravel events</title>
      <link>https://www.wintertricks.com/tricks/how-to-prevent-a-model-from-saving-using-laravel-events</link>
      <description>In the boot() method of your plugin, add this snippet:
or the preferred method:</description>
      <content:encoded><![CDATA[<p>In the <code>boot()</code> method of your plugin, add this snippet:</p>
<pre><code>Event::listen('eloquent.saving: System\Models\RequestLog', function ($model) {
    if (str_ends_with($model-&gt;url, '/bad-url')) {
        return false;
    }   
});</code></pre>
<p>or the preferred method:</p>
<pre><code>System\Models\RequestLog::saving(function ($model) {
    if (str_ends_with($model-&gt;url, '/bad-url')) {
        return false;
    }
}); </code></pre>]]></content:encoded>
    </item>
    <item>
      <title>Add links on exception-page to open error-line in IDE</title>
      <link>https://www.wintertricks.com/tricks/add-links-on-exception-page-to-open-error-line-in-ide</link>
      <description>Change the following lines in file modules/system/views/exception.php:
Line 21
old:
new:
Line 59
old:
new:
This link is for sublime text but can changed for phpstorm, vcode and other easily.
Now you have to register a custom protocol handler.
On...</description>
      <content:encoded><![CDATA[<p>Change the following lines in file modules/system/views/exception.php:</p>
<p>Line 21
old:</p>
<pre><code>&lt;p&gt;&lt;?=$exception-&gt;getFile()?&gt; &lt;span&gt;line&lt;/span&gt; &lt;?=$exception-&gt;getLine()?&gt;&lt;/p&gt;</code></pre>
<p>new:</p>
<pre><code>&lt;p&gt;
    &lt;a href="subl://open?url=file://&lt;?=$exception-&gt;getFile()?&gt;&amp;line=&lt;?=$exception-&gt;getLine()?&gt;"&gt;
        &lt;?=$exception-&gt;getFile()?&gt; &lt;span&gt;line&lt;/span&gt; &lt;?=$exception-&gt;getLine()?&gt;
    &lt;/a&gt;
&lt;/p&gt;</code></pre>
<p>Line 59
old:</p>
<pre><code>&lt;td&gt;&lt;?=$stackItem-&gt;file?&gt;&lt;/td&gt;</code></pre>
<p>new:</p>
<pre><code>&lt;td&gt;
    &lt;?php
        $file = (dirname(dirname(dirname(dirname(__FILE__)))));
        $file = str_replace('~', $file, $stackItem-&gt;file);
    ?&gt;
    &lt;a href="subl://open?url=file://&lt;?=$file;?&gt;&amp;line=&lt;?=$stackItem-&gt;line;?&gt;"&gt;
        &lt;b&gt;&lt;?=$stackItem-&gt;file?&gt;&lt;/b&gt;
    &lt;/a&gt;
&lt;/td&gt;</code></pre>
<p>This link is for sublime text but can changed for phpstorm, vcode and other easily.
Now you have to register a custom protocol handler.</p>
<p>On linux create a file "subl-url-handler" in a destination of your choice</p>
<pre><code>#!/usr/bin/env bash
arg=${1}

if [[ $arg == *"column"* ]]; then
    pattern=".*file(:\/\/|\=)(.*)&amp;line=(.*)&amp;column=(.*)"
else
    pattern=".*file(:\/\/|\=)(.*)&amp;line=(.*)"
fi

file=$(echo "${arg}" | sed -r "s/${pattern}/\2/")
line=$(echo "${arg}" | sed -r "s/${pattern}/\3/")
column=$(echo "${arg}" | sed -r "s/${pattern}/\4/")

if [ $column == "" ]; then
    DISPLAY=:0.0 /opt/sublime_text/sublime_text $file:$line
else
    DISPLAY=:0.0 /opt/sublime_text/sublime_text $file:$line:$column
fi</code></pre>
<p>then create a file /usr/share/applications/subl-url-handler.desktop</p>
<pre><code>[Desktop Entry]
Version=1.0
Type=Application
Name=subl URL Handler
Comment=Handle URL Scheme subl://open?url=@file&amp;line=@line
Icon=subl
NoDisplay=true
Categories=TextEditor;Utility;
Exec=/path/to/subl-url-handler %u
Terminal=false
MimeType=x-scheme-handler/subl;
X-Desktop-File-Install-Version=0.22</code></pre>
<p>and now run "sudo update-desktop-database" or "update-desktop-database" if you are root</p>
<p>Mac-user can take a look at <a href="https://github.com/asuth/subl-handler">https://github.com/asuth/subl-handler</a></p>
<p>Windows-user can find tipps at <a href="https://github.com/Octarine-Phaneron/custom_protocol">https://github.com/Octarine-Phaneron/custom_protocol</a></p>]]></content:encoded>
    </item>
    <item>
      <title>Loading a page in a popup</title>
      <link>https://www.wintertricks.com/tricks/loading-a-page-in-a-popup</link>
      <description>The purpose of this trick is to load a page (its content only) in a dialog window.  
We will need three parts : 

an Ajax handler to manage the page loading
a popup partial
some JavaScript to handle the dialog...</description>
      <content:encoded><![CDATA[<p>The purpose of this trick is to load a page (its content only) in a dialog window.  </p>
<p>We will need three parts : </p>
<ul>
<li>an Ajax handler to manage the page loading</li>
<li>a popup partial</li>
<li>some JavaScript to handle the dialog open/close </li>
</ul>
<blockquote>
<p>This tricks use <code>Alpine JS</code> to handle the dialog closing by clicking the cancel button or outside the dialog.
You can easily replace @click attributes by vanilla JavaScript events.</p>
</blockquote>
<h3>Add Ajax handler to your layout</h3>
<p>This handler will load a page of the site whose url will be given with a <code>data-request-data</code> attribute, and the push a partial refresh for the popup content.   </p>
<pre><code class="language-php">function onLoadPopUp()
{
    $pageUrl = post('url');
    $content = '&lt;h1&gt;Nothing to load ...&lt;/h1&gt;';
    $title = 'My Popup';

    if ($pageUrl) {
        $handlerController = new Cms\Classes\Controller;

        $router = new \Cms\Classes\Router(\Cms\Classes\Theme::getActiveTheme());
        $page = $router-&gt;findByUrl($pageUrl);
        $page-&gt;layout = null;

        // if the page loaded is a static page from Winter.Pages plugin 
        // and make use of placeholders and/or customs fields, 
        // then you need an "empty" layout repeating your defintions for thoses.
        // $page-&gt;layout = 'empty';

        $content = $handlerController-&gt;runPage($page, false);
        $title = $page-&gt;meta_title ?: $page-&gt;title;
    }

    $this['popupTitle'] = $title;
    $this['popupContent'] = $content;

    return [
        '#dialogContent' =&gt; $this-&gt;renderPartial('popup/_content')
    ];
}</code></pre>
<h3>Add popup's partials</h3>
<p>The two partials defining the popup and its content.</p>
<pre><code>? themes
 ┗ ? yourtheme
   ┗ ? partials
     ┗ ? popup
       ┃ ? _content.htm
       ┗ ? default.htm</code></pre>
<p>1 - <strong>partials/popup/default.htm file :</strong></p>
<pre><code class="language-twig">&lt;dialog id="dialog"&gt;
    &lt;div class="dialog--container" id="dialogContent" @click.outside="closeDialog()"&gt;
    &lt;/div&gt;
&lt;/dialog&gt;</code></pre>
<p>2 - <strong>partials/popup/_content.htm file :</strong></p>
<pre><code class="language-twig">&lt;div class="dialog--headerbar"&gt;
    &lt;span class="dialog--title"&gt;{{ popupTitle }}&lt;/span&gt;
    &lt;button class="btn--cancel" @click="closeDialog()" type="reset" aria-label="Cancel"&gt;
        Cancel
    &lt;/button&gt;
&lt;/div&gt;
&lt;div class="dialog--content"&gt;
    {{ popupContent | raw }}
&lt;/div&gt;</code></pre>
<p>3 - <strong>In your layout, add :</strong> </p>
<pre><code class="language-php">{% partial 'popup/default' %}</code></pre>
<h3>Add some Javascript to show/hide the dialog popup in your theme's asset</h3>
<p>These functions are intended to manage the display of an HTML <code>&lt;dialog&gt;</code> element.  </p>
<pre><code class="language-js">window.openDialog = () =&gt; {
    document.querySelector('#dialog').showModal()
}
window.closeDialog = () =&gt; {
    document.querySelector('#dialog[open]').close()
}</code></pre>
<h3>Add the Ajax handler trigger</h3>
<p>On a link or a button, allows the triggering of the Ajax handler and the opening of the dialog.
In this example the page with the url <code>/thepageurl</code> will be loaded, it must be accessible to the site visitors.  </p>
<pre><code class="language-twig">&lt;a class="..."
    data-request="onLoadPopUp"
    data-request-data="url: '/thepageurl'"
    data-request-success="openDialog()"
&gt;Link text&lt;/a&gt;</code></pre>]]></content:encoded>
    </item>
    <item>
      <title>Purging a huge amount of files from public storage.</title>
      <link>https://www.wintertricks.com/tricks/purging-a-huge-amount-of-files-from-public-storage</link>
      <description>If you need to purge a huge amount of files from the storage/app/uploads/public folder, the framework can be used but the process can be really slow (ask Luke Towers).
In such cases, you can generate the full path and purge...</description>
      <content:encoded><![CDATA[<p>If you need to purge a huge amount of files from the <code>storage/app/uploads/public</code> folder, the framework can be used but the process can be really slow (ask Luke Towers).</p>
<p>In such cases, you can generate the full path and purge the files using the technique below:</p>
<ol>
<li>build your file list using tinker or an SQL query (you just need the <code>disk_name</code> column)</li>
<li>dump that list in a file called <code>fileList.txt</code></li>
<li>create the script below</li>
</ol>
<p>bulk_purge.sh</p>
<pre><code>#!/bin/bash

# app root to reach the sorage, uses current directory by default
appRoot=$(pwd)

# relative path to the public uploads
publicPath="storage/app/uploads/public"

while read file; do
    echo "${appRoot}/${publicPath}/${file:0:3}/${file:3:3}/${file:6:3}/$file"
done

find ${appRoot}/${publicPath} -type d -empty | sort -nr | xargs -n1 rmdir </code></pre>
<ol start="4">
<li>run the following command in your terminal:</li>
</ol>
<pre><code>cat fileList.txt | bash bulk_purge.sh</code></pre>]]></content:encoded>
    </item>
    <item>
      <title>Test if partial / component / content file exists before using it.</title>
      <link>https://www.wintertricks.com/tricks/test-if-partial-component-content-file-exists-before-using-it</link>
      <description/>
      <content:encoded><![CDATA[<pre><code class="language-twig">{% if content("myContent") %}
  {% content "myContent" %}
{% else %}
  &lt;other content here&gt;
{% endif %}</code></pre>
<pre><code class="language-twig">{% if partial("myPartial") %}
  {% partial "myPartial" %}
{% else %}
  &lt;other content here&gt;
{% endif %}</code></pre>
<pre><code class="language-twig">{% if component("myComponent") %}
  {% component "myComponent" %}
{% else %}
  &lt;other content here&gt;
{% endif %}</code></pre>]]></content:encoded>
    </item>
    <item>
      <title>Extend Froala editor</title>
      <link>https://www.wintertricks.com/tricks/extend-froala-editor</link>
      <description>Example of how to extend the Froala editor</description>
      <content:encoded><![CDATA[<p>Example of how to extend the Froala editor</p>
<pre><code class="language-php">use Backend\Classes\Controller;
public function boot()
{
    // extend richeditor with custom color picker
    Controller::extend(function ($widget) {
        $widget-&gt;addJs('/plugins/aic/globals/assets/js/froala-color-picker.js');
    });
}</code></pre>
<pre><code class="language-javascript">/*
|------------------
| Extend Richeditor
|------------------
 */
+function ($) { "use strict";
    $(document).render(function() {
        if ($.FroalaEditor) {
            $.FroalaEditor.DEFAULTS = $.extend($.FroalaEditor.DEFAULTS, {
                colorsText: [
                    'REMOVE',
                    '#333333',
                    '#848484',
                    '#E0DFDD',
                    '#F8F6F3',
                    '#FFFFFF',
                    '#FF1616',
                    '#FD5E2B',
                    '#FFE836',
                    '#1EBF80',
                    '#2B7FFD',
                    '#EAF3FF',
                    '#E9B4A6'
                ]
            });
        }
    })
}(window.jQuery);</code></pre>]]></content:encoded>
    </item>
    <item>
      <title>Dynamically Insert a field in an existing form at a given position.</title>
      <link>https://www.wintertricks.com/tricks/dynamically-insert-a-field-in-an-existing-form-at-a-given-position</link>
      <description>Note: credit to @jaxwilko
You can add the following helper method in your plugin's boot method to make this easier:
The example above would become:</description>
      <content:encoded><![CDATA[<pre><code class="language-php">Event::listen('backend.form.extendFieldsBefore', function ($widget) {
    if (!$widget-&gt;getController() instanceof MyController || !$widget-&gt;model instanceof MyModel {
        return; 
    }
    $position = 4;
    $before = $widget-&gt;fields;
    $after = array_splice($before, $position-1);

    $newFields = [
        'myFirstField' =&gt; [
            'type' =&gt; 'text',
            'label' =&gt; 'My First Field',
        ],
        'mySecondField' =&gt; [
            'type' =&gt; 'switch',
            'label' =&gt; 'My Second Field',
        ],
    ];      
    $widget-&gt;fields = array_merge($before, $newFields, $after);
});</code></pre>
<p>Note: credit to @jaxwilko</p>
<p>You can add the following helper method in your plugin's boot method to make this easier:</p>
<pre><code class="language-php">\Backend\Widgets\Form::extend(function () {
    $this-&gt;addDynamicMethod('insertFieldsAtPosition', function ($fields, $position) {
        $after = array_splice($this-&gt;fields, $position-1);
        $this-&gt;fields = array_merge($this-&gt;fields, $fields, $after);
    }); 
}, true);</code></pre>
<p>The example above would become:</p>
<pre><code class="language-php">Event::listen('backend.form.extendFieldsBefore', function ($widget) {
    if (!$widget-&gt;getController() instanceof MyController || !$widget-&gt;model instanceof MyModel {
            return; 
    }
    $widget-&gt;insertFieldsAtPosition([
        'myFirstField' =&gt; [
            'type' =&gt; 'text',
            'label' =&gt; 'My First Field',
        ],
        'mySecondField' =&gt; [
            'type' =&gt; 'switch',
            'label' =&gt; 'My Second Field',
        ],
    ], position:4); 
});</code></pre>]]></content:encoded>
    </item>
    <item>
      <title>How to save belongsTo relation in one form without using relation form widget on create</title>
      <link>https://www.wintertricks.com/tricks/how-to-save-belongsto-relation-in-one-form-without-using-relation-form-widget-on-create</link>
      <description>define your fields in fields.yaml as</description>
      <content:encoded><![CDATA[<pre><code>public function formExtendModel($model)
    {

         if ($this-&gt;action == 'create') {
             $model-&gt;address = new \Company\Plugin\Models\Address();
         }

         return $model;
    }
</code></pre>
<p>define your fields in fields.yaml as</p>
<pre><code>fields:
    address[streetname]:
                        label: Name
            type: text
    address[housenumber]:
                        label: House Number
            type: text
   address[zip]:
                        label: Zip
            type: text</code></pre>]]></content:encoded>
    </item>
    <item>
      <title>AJAX requests in Plugin Settings</title>
      <link>https://www.wintertricks.com/tricks/ajax-requests-in-plugin-settings</link>
      <description>

Create your Settings plugin as usual, but use the url instead of class property at the registerSettings method.


Create a controller: Settings.php:


Create settings folder in controllers folder with update.htm:


Now you can call your Ajax functions.</description>
      <content:encoded><![CDATA[<ol>
<li><a href="https://wintercms.com/docs/v1.2/docs/plugin/settings#settings-link-registration">Create your Settings plugin as usual</a>, but use the url instead of class property at the registerSettings method.</li>
<li>Create a controller: Settings.php:</li>
</ol>
<pre><code>&lt;?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' =&gt; 'Settings',
        'form' =&gt; "$/author/plugin/models/settings/fields.yaml",
        'modelClass' =&gt; 'Author\Plugin\Models\Settings',
        'defaultRedirect' =&gt; '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-&gt;update();
    }

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

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

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

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

    public function onMyFunction()
    {
    }

}</code></pre>
<ol start="3">
<li>Create settings folder in controllers folder with update.htm:</li>
</ol>
<pre><code>&lt;?php Block::put('breadcrumb') ?&gt;
    &lt;ul&gt;
        &lt;li&gt;&lt;?= e($this-&gt;pageTitle) ?&gt;&lt;/li&gt;
    &lt;/ul&gt;
&lt;?php Block::endPut() ?&gt;

&lt;?= Form::open(['class' =&gt; 'layout']) ?&gt;

    &lt;div class="layout-row"&gt;
        &lt;?= $this-&gt;formRender() ?&gt;
    &lt;/div&gt;

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

&lt;?= Form::close() ?&gt;</code></pre>
<p>Now you can call your Ajax functions.</p>]]></content:encoded>
    </item>
    <item>
      <title>Has Many Through ... Pivot</title>
      <link>https://www.wintertricks.com/tricks/has-many-through-pivot</link>
      <description>Has Many Through Pivot means: accessing a distant “one to many” relationship though another relationship that uses a Pivot table (even a polymorphic one) to connect.

Imagine a site where: 

users (User model from Winter.user plugin) can belongs to many...</description>
      <content:encoded><![CDATA[<p><em>Has Many Through Pivot</em> means: accessing a distant “one to many” relationship though another relationship that uses a Pivot table (even a polymorphic one) to connect.
</p>
<p>Imagine a site where: </p>
<ul>
<li>users (<code>User</code> model from Winter.user plugin) can belongs to many companies (<code>Company</code> model)</li>
<li>and each <code>Company</code> has many <code>SalePoint</code>
   </li>
</ul>
<p>How we can attach a <code>SalePoint</code> to a <code>User</code>? A <code>CompanyUser</code> pivot model will help us.
It’s basically a Many-To-Many relation. There are many Users, and many Companies.
   </p>
<h3>First step: Make a CompanyUser Pivot</h3>
<p>Doing this allows to access directly to the pivot table information without the need of raw DB calls. You can use Artisan to make it, or just write it down.
  </p>
<pre><code>php artisan create:model Acme.MyPlugin CompanyUserPivot --pivot  --no-migration </code></pre>
<p>     </p>
<pre><code class="language-php">&lt;?php

namespace Acme\MyPlugin\Models;

use Winter\Storm\Database\Pivot;

/**
 * Company-User Pivot Model
 */
class CompanyUserPivot extends Pivot
{
    /**
     * @var string The database table used by the model.
     */
    public $table = 'acme_myplugin_company_user';

    public $belongsTo = [
        'user' =&gt; \Winter\User\Models\User::class,
        'company' =&gt; \Acme\MyPlugin\Models\Company::class,
    ];

    public $hasManyThrough = [
        'salepoints' =&gt; [
            \Acme\MyPlugin\Models\SalePoint::class,
            'through' =&gt; \Acme\MyPlugin\Models\Company::class,
        ]
    ];
}</code></pre>
<h3>Second Step: Company Model</h3>
<p>Here we need to tell the <code>Company</code> model that we will use our newly created <code>CompanyUserPivot</code> model to connect it to the User model.
  </p>
<pre><code class="language-php">// Plugins/Acme/MyPlugin/Models/Company.php

// Add used class
use Winter\User\Models\User;

// Add relationship
public $belongsToMany = [
    'users' =&gt; [
        User::class,
        'table' =&gt; 'acme_myplugin_company_user',
        'pivotModel' =&gt; 'Acme\MyPlugin\Models\CompanyUserPivot',
    ],
];</code></pre>
<h3>Third Step: Define the inverse for the User Model</h3>
<p>As the <code>User</code> model is already defined, we need to extend it to add relations from our plugin's <code>boot()</code> method.
  </p>
<pre><code class="language-php">// Plugins/Acme/MyPlugin/Plugin.php

// Add used class
use Acme\MyPlugin\Models\Company;
use Winter\User\Models\User;

// Extend User relationships
public function boot(): void
{
    User::extend(function ($model) {
        $model-&gt;belongsToMany = array_merge(
            $model-&gt;belongsToMany, [
                'companies' =&gt; [
                    Company::class,
                    'table' =&gt; 'acme_myplugin_company_user',
                    'pivotModel' =&gt; 'Acme\MyPlugin\Models\CompanyUserPivot',
                    'scope' =&gt; 'isActive'
                ],
            ]
        );
    });
}</code></pre>
<h3>Last Step: Add a touch of magic</h3>
<p>Don’t close our <code>Plugin.php</code> model in your editor just yet!
Now we have to tell our <code>User</code> model to access the <code>SalePoint</code> one using a Has Many Through relationship, but not from <code>Company</code> model, but rather our <code>CompanyUserPivot</code> model.
  </p>
<pre><code class="language-php">// Plugins/Acme/MyPlugin/Plugin.php

// Add used class
use Acme\MyPlugin\Models\Company;
use Acme\MyPlugin\Models\SalePoint;
use Winter\User\Models\User;

// Extend User relationships
public function boot(): void
{
    User::extend(function ($model) {
        $model-&gt;belongsToMany = array_merge(
            $model-&gt;belongsToMany, [
                'companies' =&gt; [
                    Company::class,
                    'table' =&gt; 'acme_myplugin_company_user',
                    'pivotModel' =&gt; 'Acme\MyPlugin\Models\CompanyUserPivot',
                    'scope' =&gt; 'isActive'
                ],
            ]
        );
        $model-&gt;hasManyThrough = array_merge(
            $model-&gt;hasManyThrough, [
                'salepoints' =&gt; [
                    SalePoint::class,
                    'through' =&gt; CompanyUserPivot::class,
                    'key' =&gt; 'user_id',
                    'throughKey' =&gt; 'company_id',
                    'otherKey' =&gt; 'id',
                    'secondOtherKey' =&gt; 'company_id',
                ]
            ]
        );
    });
}</code></pre>
<p>
With that, you can access to the "SalePoints" from the <code>User</code> model with no problems at all, no matter how many sale points it may have.
As a bonus, we aren’t creating any new class hard to maintain, only what Winter gives us.</p>]]></content:encoded>
    </item>
    <item>
      <title>Using Model::observe() to manage Model events</title>
      <link>https://www.wintertricks.com/tricks/using-modelobserve-to-manage-model-events</link>
      <description>Laravel has a nice way of registering an Observer class to manage Model events:
You can monitor all Laravel events: retrieved, creating, created, updating, updated, saving, saved, restoring, restored, replicating, deleting, deleted, forceDeleting, forceDeleted
First, create an Observer class like...</description>
      <content:encoded><![CDATA[<p>Laravel has a nice way of registering an Observer class to manage Model events:</p>
<p>You can monitor all Laravel events: retrieved, creating, created, updating, updated, saving, saved, restoring, restored, replicating, deleting, deleted, forceDeleting, forceDeleted</p>
<p>First, create an Observer class like this:</p>
<pre><code class="language-php">class MyModelObserver
{
    public function created($model) 
    {
        ...
    }
    public function updated($model) 
    {
        ...
    }
    public function deleted($model) 
    {
        ...
    }
}</code></pre>
<p>Then, simply register the Observer class with your model(s) in the <code>boot()</code> method of your plugin:</p>
<pre><code class="language-php">public function boot()
{
    MyModel::observe(MyModelObserver::class);
}</code></pre>
<p>An Observer class may be used by multiple models if needed:</p>
<pre><code class="language-php">public function boot()
{
    MyModel::observe(MyModelObserver::class);
    MyOtherModel::observe(MyModelObserver::class);
}</code></pre>
<p>You can also add multiple Oberver classes to a model:</p>
<pre><code class="language-php">public function boot()
{
    MyModel::observe([Observer1::class, Observer2::class, ...]);
}</code></pre>]]></content:encoded>
    </item>
    <item>
      <title>Override the mail content of the users mail</title>
      <link>https://www.wintertricks.com/tricks/override-the-mail-content-of-the-users-mail</link>
      <description>Written with AI for additional context
Rebrand vendor plugin mails without touching the plugin
Category: Mail / Events
Works with: Winter CMS 1.1+ (any plugin that sends view-based mails, e.g. Winter.User)
The problem
Plugins like Winter.User send transactional mails (winter.user::mail.restore,...</description>
      <content:encoded><![CDATA[<p>Written with AI for additional context</p>
<h1>Rebrand vendor plugin mails without touching the plugin</h1>
<p><strong>Category:</strong> Mail / Events
<strong>Works with:</strong> Winter CMS 1.1+ (any plugin that sends view-based mails, e.g. Winter.User)</p>
<h2>The problem</h2>
<p>Plugins like <strong>Winter.User</strong> send transactional mails (<code>winter.user::mail.restore</code>, <code>winter.user::mail.activate</code>) using their own bundled templates. They look generic, and you usually want them in your own branding, layout and tone of voice.</p>
<p>The usual options all have downsides:</p>
<ul>
<li><strong>Editing the vendor views</strong> — gone on the next <code>composer update</code>.</li>
<li><strong>Overriding templates in the backend (Settings → Mail templates)</strong> — works, but the content now lives in the database instead of your git repository. No code review, no deploys, no history, and every environment (local, staging, production) has to be kept in sync by hand.</li>
<li><strong>Forking the plugin</strong> — a maintenance burden for what is essentially a cosmetic change.</li>
</ul>
<p>What you actually want: the vendor plugin keeps <em>triggering</em> its mails exactly as it does today, but the <em>content</em> comes from your own git-tracked templates in your own plugin.</p>
<h2>The trick</h2>
<p>Winter's own mail system renders view-based mails through the global <code>mailer.beforeAddContent</code> event — the System module listens to it to resolve and render the template, and Winter.Translate listens to it for localization. Because event listeners run in priority order and returning <code>false</code> halts propagation, you can register your own listener at a <strong>higher priority</strong>, swap the vendor view code for your own, add the content yourself, and return <code>false</code> so the default handlers never run — but <em>only</em> for the mails you map. Everything else falls through untouched.</p>
<p>In your plugin's <code>boot()</code> method:</p>
<pre><code class="language-php">Event::listen('mailer.beforeAddContent', function ($mailer, $message, $view, $data, $raw, $plain) {
    static $map = [
        'winter.user::mail.restore'  =&gt; 'acme.site::mail.restore',
        'winter.user::mail.activate' =&gt; 'acme.site::mail.activate',
    ];

    // Only the two view-based vendor mails we rebrand; leave raw mails and
    // everything else to the default handlers.
    if ($raw !== null || !is_string($view) || !isset($map[$view])) {
        return;
    }

    $code = $map[$view];

    MailManager::instance()-&gt;addContentToMailer($message, $code, $data);

    return false; // branded content added — skip the vendor template
}, 100);</code></pre>
<p>Your own templates (<code>acme.site::mail.restore</code>, …) are registered the normal way via <code>registerMailTemplates()</code> in your Plugin.php and live as <code>.htm</code> files in your plugin — versioned, reviewable, deployable.</p>
<h2>How it works</h2>
<ol>
<li>Winter.User calls <code>Mail::send('winter.user::mail.restore', …)</code> as usual — nothing changes on the vendor side.</li>
<li>The Mailer fires <code>mailer.beforeAddContent</code> before resolving the template content.</li>
<li>Your listener runs <strong>first</strong> (priority 100 beats the default priority 0 of the System/Translate listeners).</li>
<li>For unmapped views or raw mails it returns nothing, so propagation continues and the framework behaves exactly as stock.</li>
<li>For a mapped view it renders <em>your</em> template into the message via <code>MailManager::addContentToMailer()</code> and returns <code>false</code>, halting the event — so the vendor template is never rendered.</li>
</ol>
<h2>Bonus: keep localization</h2>
<p>If you run a multilingual site with Winter.Translate, you also bypass its localization handler — so resolve the locale-suffixed variant yourself before adding content:</p>
<pre><code class="language-php">$locale = !empty($data['_current_locale']) ? $data['_current_locale'] : App::getLocale();

// Prefer a locale-suffixed variant (restore-fr, activate-en, …), else the base.
$localized = EventRegistry::instance()-&gt;getLocalizedView($mailer-&gt;getViewFactory(), $code, $locale);

MailManager::instance()-&gt;addContentToMailer($message, $localized ?: $code, $data);</code></pre>
<p>(<code>EventRegistry</code> here is <code>Winter\Translate\Classes\EventRegistry</code> — the same class Winter.Translate uses internally, so your naming convention for localized templates stays identical to the rest of your site.)</p>
<h2>When to use this</h2>
<ul>
<li>You want vendor transactional mails in your own branding <strong>and</strong> you want those templates in version control rather than in the database.</li>
<li>You're rebranding a <em>subset</em> of mails and want everything else to keep stock behavior.</li>
<li>You can't or don't want to fork/patch the vendor plugin.</li>
</ul>
<h2>When <em>not</em> to use this</h2>
<ul>
<li>If database-managed templates are fine for your workflow, simply overriding the template content in <strong>Settings → Mail templates</strong> is less code.</li>
<li>If you need to change <em>when</em> or <em>to whom</em> a mail is sent (not just its content), look at the plugin's own events instead — this hook only controls content.</li>
</ul>
<h2>Gotchas</h2>
<ul>
<li>Guard against <code>$raw</code> mails and non-string views (Winter also supports <code>['html' =&gt; …, 'text' =&gt; …]</code> view arrays) — the early return in the snippet handles this.</li>
<li>Keep the listener registration in <code>boot()</code>, not <code>register()</code>, so all mail infrastructure is available.</li>
<li>If another plugin also registers a high-priority listener on this event, priorities decide who wins — pick a number consciously</li>
</ul>]]></content:encoded>
    </item>
    <item>
      <title>How to add a canonical link to your layout in twig</title>
      <link>https://www.wintertricks.com/tricks/how-to-add-a-canonical-link-to-your-layout-in-twig</link>
      <description>Add this to the  section of your layout:</description>
      <content:encoded><![CDATA[<p>Add this to the  section of your layout:</p>
<pre><code>&lt;link rel="canonical" href="{{ url_current() | lower }}" /&gt;</code></pre>]]></content:encoded>
    </item>
    <item>
      <title>Add a relation to an existing plugin's controller</title>
      <link>https://www.wintertricks.com/tricks/add-a-relation-to-an-existing-plugins-controller</link>
      <description>Let's assume the following:

There is a plugin named "pluginAuthor.pluginName" you want to extend;
This plugin has a controller named "pluginController";
You want to add a new relation named "myRelation" to this controller;
Your plugin is named "myAuthor.myPlugin";

Add the...</description>
      <content:encoded><![CDATA[<p>Let's assume the following:</p>
<ul>
<li>There is a plugin named "pluginAuthor.pluginName" you want to extend;</li>
<li>This plugin has a controller named "pluginController";</li>
<li>You want to add a new relation named "myRelation" to this controller;</li>
<li>Your plugin is named "myAuthor.myPlugin";</li>
</ul>
<p>Add the following code to your plugin's boot() method:</p>
<pre><code>pluginController::extend( function ($controller) {
    $new_relation = $controller-&gt;makeConfigFromArray([
        'myrelation' =&gt; [
            'label' =&gt; 'My Relation',
            'view' =&gt; [
                'list' =&gt; '$/myauthor/myplugin/models/myrelation/columns.yaml',
                'toolbarButtons' =&gt; 'add|create|remove',
                'showSearch' =&gt; true,
             ],
             'manage' =&gt; [
                 'list' =&gt; '$/myauthor/myplugin/models/myrelation/columns.yaml',
                 'form' =&gt; '$/myauthor/myplugin/models/myrelation/fields.yaml',
                 'showSearch' =&gt; true,
             ],
         ]
    ]);

    $controller-&gt;relationConfig = $controller-&gt;mergeConfig(
        $controller-&gt;relationConfig, 
        $new_relation
    );</code></pre>
<p>Alternatively, you can create a <code>config_relation.yaml</code> file with the new relation(s) and use this code:</p>
<pre><code>pluginController::extend( function ($controller) {
    $controller-&gt;relationConfig = $controller-&gt;mergeConfig(
        $controller-&gt;relationConfig,
        '$/myAuthor/myPlugin/config/config_relation.yaml'
    );
});</code></pre>]]></content:encoded>
    </item>
    <item>
      <title>Add filtering to a ReorderController</title>
      <link>https://www.wintertricks.com/tricks/add-filtering-to-a-reordercontroller</link>
      <description>Add this snippet to your controller's _reorder_toolbar.htm partial:
Add this to your Controller class:</description>
      <content:encoded><![CDATA[<p>Add this snippet to your controller's <code>_reorder_toolbar.htm</code> partial:</p>
<pre><code>    &lt;input name="filter-records" type="text" class="form-control icon search growable"
        data-request="onFilterRecords"
        data-track-input
    /&gt;</code></pre>
<p>Add this to your Controller class:</p>
<pre><code>    public function onFilterRecords()
    {   
        $reorderController = $this-&gt;asExtension('ReorderController');
        $reorderController-&gt;reorder();
        return [
            '#reorderRecords' =&gt; $reorderController-&gt;reorderMakePartial('records', ['records' =&gt; $reorderController-&gt;vars['reorderRecords']]),
        ];
    }

    public function reorderExtendQuery($query)
    {   
        if ($term = Input::get('filter-records')) {
            $query-&gt;where('name', 'like', "%$term%");
        }
    }</code></pre>]]></content:encoded>
    </item>
    <item>
      <title>Get all filtered records by a List Widget</title>
      <link>https://www.wintertricks.com/tricks/get-all-filtered-records-by-a-list-widget</link>
      <description>If you want to take an action on all currently filtered records from your Controller implementing the ListController behavior, add this method to your controller:</description>
      <content:encoded><![CDATA[<p>If you want to take an action on all currently filtered records from your Controller implementing the ListController behavior, add this method to your controller:</p>
<pre><code>    public function onGetFilteredRecords()
    {
        $this-&gt;makeLists();
        $listWidget = $this-&gt;asExtension('ListController')-&gt;listGetWidget();

        $query = $listWidget-&gt;prepareQuery();
        $records = $query-&gt;get();

        // do something with $records
    }</code></pre>]]></content:encoded>
    </item>
    <item>
      <title>How to translate fields added dynamically to a Model (or CMS Page)</title>
      <link>https://www.wintertricks.com/tricks/how-to-translate-fields-added-dynamically-to-a-model-or-cms-page</link>
      <description>Since the Winter.Translate plugin uses the backend.form.extendFieldsBefore event to replace regular form fields with their multi-lang equivalent, new fields must be added using this event as well, otherwise they won't be translatable.
In your plugin's boot() method, create the new...</description>
      <content:encoded><![CDATA[<p>Since the <code>Winter.Translate</code> plugin uses the <code>backend.form.extendFieldsBefore</code> event to replace regular form fields with their multi-lang equivalent, new fields must be added using this event as well, otherwise they won't be translatable.</p>
<p>In your plugin's <code>boot()</code> method, create the new field and add it to the model's translatable property array:</p>
<pre><code class="language-php">Event::listen('backend.form.extendFieldsBefore', function($widget) {
   $widget-&gt;config['fields']['myField'] =
   $widget-&gt;tabs['fields']['myField'] = [
      'label' =&gt; 'My New Field',
      'type' =&gt; text,
      'tab' =&gt; 'myTab'
   ];
});

YourModel::extend(function($model) {
   if (!$model-&gt;propertyExists('translatable')) {
      $model-&gt;addDynamicProperty('translatable', []);
   }

   $model-&gt;translatable = array_merge($model-&gt;translatable, ['myField']);
     if (!$model-&gt;isClassExtendedWith('Winter.Translate.Behaviors.TranslatableModel')) {
        $model-&gt;extendClassWith('Winter.Translate.Behaviors.TranslatableModel');
   }
});</code></pre>]]></content:encoded>
    </item>
    <item>
      <title>Using Pluralization with String Translations</title>
      <link>https://www.wintertricks.com/tricks/using-pluralization-with-string-translations</link>
      <description>Laravel's trans_choice() provides the means to correctly pluralize strings in different locales with very flexible rules.
First, create your translation strings:
Use it in twig with the transchoice filter:
Use it in PHP code with the trans_choice() function:</description>
      <content:encoded><![CDATA[<p>Laravel's <code>trans_choice()</code> provides the means to correctly pluralize strings in different locales with very flexible rules.</p>
<p>First, create your translation strings:</p>
<pre><code>/plugins/author/plugin/lang/en/lang.php:

&lt;?php return [
   'choice' =&gt; '{0} There are no apples|{1} There is one apple|[2,Inf] There are :count apples',
];</code></pre>
<pre><code>/plugins/author/plugin/lang/fr/lang.php

&lt;?php return [
   'choice' =&gt; "{0} Il n'y a pas de pomme|{1} Il y a une pomme|[2,Inf] Il y a :count pommes",
];</code></pre>
<p>Use it in twig with the <code>transchoice</code> filter:</p>
<pre><code>Example in twig:

{{ 'author.plugin::lang.choice' | transchoice(0) }}
{{ 'author.plugin::lang.choice' | transchoice(1) }}
{{ 'author.plugin::lang.choice' | transchoice(10) }}</code></pre>
<p>Use it in PHP code with the <code>trans_choice()</code> function:</p>
<pre><code>Example in PHP code:

$zero = trans_choice('author.plugin::lang.choice', 0);
$one = trans_choice('author.plugin::lang.choice', 1);
$ten = trans_choice('author.plugin::lang.choice', 10);</code></pre>]]></content:encoded>
    </item>
    <item>
      <title>Render twig content from a string</title>
      <link>https://www.wintertricks.com/tricks/render-twig-content-from-a-string</link>
      <description>If you want to render twig content contained in a string (a textarea field for example), you can do so with a twig filter as shown below:
Add this twig filter to your Plugin.php:
You can now render any twig...</description>
      <content:encoded><![CDATA[<p>If you want to render twig content contained in a string (a textarea field for example), you can do so with a twig filter as shown below:</p>
<p>Add this twig filter to your Plugin.php:</p>
<pre><code>use Cms\Classes\Controller;

public function registerMarkupTags()
{   
    return [
        'filters' =&gt; [
            'twig' =&gt; function ($content, $vars=[]) {
                $controller = Controller::getController() ?: new Controller;
                $vars = array_merge($vars, $controller-&gt;vars);
                $env = $controller-&gt;getTwig();
                return $env-&gt;createTemplate($content)-&gt;render($vars);
            },
        ],
    ];
}</code></pre>
<p>You can now render any twig content in your markup as shown below:</p>
<pre><code>{{ fieldWithTwigContent | twig }}</code></pre>]]></content:encoded>
    </item>
    <item>
      <title>Use message translations in PHP code</title>
      <link>https://www.wintertricks.com/tricks/use-message-translations-in-php-code</link>
      <description>If you need to translate something with Rainlab.Translate in the backend from PHP, use the following code:
If you need to translate something with Laravel default translation in the backend from PHP, use the following code:
The current locale will...</description>
      <content:encoded><![CDATA[<p>If you need to translate something with <code>Rainlab.Translate</code> in the backend from PHP, use the following code:</p>
<pre><code class="language-php">use Winter\Translate\Models\Message;

// use Winter's Message translation
$translated = Message::trans('key');</code></pre>
<p>If you need to translate something with Laravel default translation in the backend from PHP, use the following code:</p>
<pre><code class="language-php">// use default Laravel helper function
$translated = trans('key');</code></pre>
<p>The current locale will be used.</p>]]></content:encoded>
    </item>
    <item>
      <title>Alternate links for multilingual sites</title>
      <link>https://www.wintertricks.com/tricks/alternate-links-for-multilingual-sites</link>
      <description>Needs the Winter.Translate plugin. Add the components like this:
Code for your html head</description>
      <content:encoded><![CDATA[<p>Needs the <a href="https://github.com/wintercms/wn-translate-plugin">Winter.Translate</a> plugin. Add the components like this:</p>
<pre><code>[localePicker]
forceUrl = 1

[alternateHrefLangElements]
</code></pre>
<p>Code for your html head</p>
<pre><code>
{% for locale, alternateUrl in alternateHrefLangElements.locales %}
      &lt;link rel="alternate" hreflang="{{ locale }}" href="{{ url(alternateUrl) }}" /&gt;
  {% endfor %}
</code></pre>]]></content:encoded>
    </item>
    <item>
      <title>Dynamic override of Settings Model fields</title>
      <link>https://www.wintertricks.com/tricks/allow-for-custom-overrides-of-settings-model</link>
      <description>Overwriting the Settings Model's getFieldConfig() method allows you to dynamically modify field configuration used for storing settings.
The following allows for overriding the configuration specified in fields.yaml only when the config key app.acme_plugin_settings is populated.</description>
      <content:encoded><![CDATA[<p>Overwriting the Settings Model's <code>getFieldConfig()</code> method allows you to dynamically modify field configuration used for storing settings.</p>
<p>The following allows for overriding the configuration specified in <code>fields.yaml</code> only when the config key <code>app.acme_plugin_settings</code> is populated.</p>
<pre><code class="language-php">&lt;?php

namespace Acme\Plugin\Models;

use Model;

class Settings extends Model
{
    public $implement = ['System.Behaviors.SettingsModel'];

    public $settingsCode = 'acme_plugin_settings';

    public $settingsFields = 'fields.yaml';

    protected $cache = [];

    protected $fieldConfig = null;

    /**
     * Returns the field configuration used by this model.
     */
    public function getFieldConfig()
    {
        if ($this-&gt;fieldConfig !== null) {
            return $this-&gt;fieldConfig;
        }

        if ($config = config('app.acme_plugin_settings', [])) {
            return $this-&gt;fieldConfig = (object) $config;
        }

        return $this-&gt;fieldConfig = $this-&gt;makeConfig($this-&gt;settingsFields);
    }
}
</code></pre>]]></content:encoded>
    </item>
    <item>
      <title>Enable SVG support in Media Manager</title>
      <link>https://www.wintertricks.com/tricks/enable-svg-support-in-media-manager</link>
      <description>The Winter CMS team will be making SVG supported by default very soon, but in the mean time, if you wish to allow SVG uploads into the Media Manager, simply add the following to your config/cms.php configuration file:</description>
      <content:encoded><![CDATA[<p>The Winter CMS team will be making SVG supported by default very soon, but in the mean time, if you wish to allow SVG uploads into the Media Manager, simply add the following to your <code>config/cms.php</code> configuration file:</p>
<pre><code class="language-php">    'fileDefinitions' =&gt; [
        'defaultExtensions' =&gt; [
            'jpg',
            'jpeg',
            'bmp',
            'png',
            'webp',
            'gif',
            'svg',
            'js',
            'map',
            'ico',
            'css',
            'less',
            'scss',
            'ics',
            'odt',
            'doc',
            'docx',
            'ppt',
            'pptx',
            'pdf',
            'swf',
            'txt',
            'ods',
            'xls',
            'xlsx',
            'eot',
            'woff',
            'woff2',
            'ttf',
            'flv',
            'wmv',
            'mp3',
            'ogg',
            'wav',
            'avi',
            'mov',
            'mp4',
            'mpeg',
            'webm',
            'mkv',
            'rar',
            'zip'
        ],
        'imageExtensions' =&gt; [
            'jpg',
            'jpeg',
            'bmp',
            'png',
            'webp',
            'gif',
            'svg',
        ],
    ],</code></pre>]]></content:encoded>
    </item>
  </channel>
  <channel>
    <title>October Trick of the day</title>
    <link>https://www.wintertricks.com</link>
    <description>octobertrickscom Trick of the day</description>
    <atom:link href="" rel="self" type="application/rss+xml"/>
    <item>
      <title>Using morphMap to migrate morph-type relations to another model</title>
      <link>https://www.wintertricks.com/tricks/using-morphmap-to-migrate-morph-type-relations-to-another-model</link>
      <description>If you need to migrate morph-type relations that store the model name in the DB, morphMap is really good for this.
That will also take care of translated model fields stored in winter_translate_attributes table.
The following morphMap migrates the relations...</description>
      <content:encoded><![CDATA[<p>If you need to migrate morph-type relations that store the model name in the DB, morphMap is really good for this.</p>
<p>That will also take care of translated model fields stored in winter_translate_attributes table.</p>
<p>The following morphMap migrates the relations from Lovata.Shopaholic plugin to OFFLINE.Mall plugin:</p>
<pre><code>use Winter\Storm\Database\Relations\Relation;

public function boot()
{
    Relation::morphMap([
        'Lovata\Shopaholic\Models\Product'  =&gt; 'OFFLINE\Mall\Models\Product',
        'Lovata\Shopaholic\Models\Category' =&gt; 'OFFLINE\Mall\Models\Category',
    ]);
}</code></pre>]]></content:encoded>
    </item>
  </channel>
</rss>
