Homepage
Main navigation
Main content
Additional information
Login / Sign up
Quality Guidelines
About
GitHub
Propose new content
Winter CMS resources and help articles
Simple and to the point. Optimized by the community.
×
Login / Sign up
Quality Guidelines
About
GitHub
Propose new content
Edit trick
Changes will be published after manual review
Title
Give your trick a describing title. Do
not
start with «How to...».
Your trick
Keep it short and concise! Markdown is supported.
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.
References
Add additional online resources to your trick
×
Name
URL
+ Add reference
Topics
If your trick fits more than one topic select multiple. Select at least one.
Backend
Plugin Development
CMS
Twig
Themes
Deployment
Tags
You can use existing tags or create new ones. Add at least one.
Submit for review
Cancel
We use cookies to measure the performance of this website. Do you want to accept these cookies?
Accept
Decline