Winter CMS resources and help articles

Simple and to the point. Optimized by the community.

Add locale field to System\Models\File

0
by mjauvin, last modified on August 22nd, 2022

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" => true 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:

use System\Models\File as FileModel;

...

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

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

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

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

        $locale = \App::getLocale();
        if (!\App::runningInBackend()) {
            $model::addGlobalScope('localized', function ($builder) use ($locale) {
                $builder->whereNull('locale')->orWhere('locale', $locale);
            });
        }
    }); 
}

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.

Discussion

0 comments

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