spatie / nova-translatable Goto Github PK
View Code? Open in Web Editor NEWMaking Nova fields translatable
Home Page: https://murze.be/making-nova-fields-translatable
License: MIT License
Making Nova fields translatable
Home Page: https://murze.be/making-nova-fields-translatable
License: MIT License
When using withFiles() to store images within a Trix field, the browser generates 404 errors when inserting the image (during edits). Example
public function fields(Request $request) {
return [
ID::make(__('ID'), 'id')->sortable(),
Translatable::make([
Text::make('title')->sortable(),
Trix::make('text')->hideFromIndex()->withFiles(env('POSTS_DISK','public')),
]),
...
]
}
The browser will try to call a POST URL /nova-api/posts/field-attachment/translations_text_xx/{uuid of post}
for each language (where xx is the language code). These URLs don't exist.
Workaround is to add hidden dummy fields for each language to ensure the URLs exist and nova can actually store the image file:
public function fields(Request $request) {
return [
ID::make(__('ID'), 'id')->sortable(),
Translatable::make([
Text::make('title')->sortable(),
Trix::make('text')->hideFromIndex()->withFiles(env('POSTS_DISK','public')),
]),
Trix::make('translations_text_en')->withFiles(env('POSTS_DISK','public'))->hideWhenCreating()->hideWhenUpdating()->hideFromDetail(),
Trix::make('translations_text_nl')->withFiles(env('POSTS_DISK','public'))->hideWhenCreating()->hideWhenUpdating()->hideFromDetail(),
...
]
}
For this workaround to work the name of the dummy fields should be "translations_<original fieldname>_<language code>
"
This will need to be fixed in the code, or clear instructions can be added to the documentation.
is there a way to make only one locale as required not all locales
can you pump the package to support spatie/laravel-translatable
v6
When a field is translatable, it can't trigger the automatic slug generation. I tried giving the Slug field ->preview('title'), ->preview('title.en') and also passing the field as an an object, that is previously defined like
$title = Text::make('Title') ->translatable();
... ->preview($title);
Using a Translatable field inside a NovaDependencyContainer field will cause the following error:
Call to undefined method Spatie\NovaTranslatable\Translatable::resolve()
Sample:
NovaDependencyContainer::make([
Translatable::make([
Trix::make('Body')
->rules('required_with:is_article,body')
->withMeta([
'extraAttributes' => [
'placeholder' => 'Body',
],
]),
])->locales(['en']),
...
])->dependsOn('is_article', 1),
Any workarounds until the awaited compatibility patch?
When adding Translatable fields to a new Panel, the Translatable fields just get added to the main Panel.
I created an example that also includes a new Panel with a regular Nova field, to show that the issue isn't related to the Panel itself. The new Panel with a Nova field does get added. The new Panel with a Translatable field does not get added, the Translatable field gets added to the main Panel instead.
...
public function fields(NovaRequest $request): array
{
return [
ID::make()->sortable(),
// Working new Panel with Nova fields
new Panel('External Fields', [
Text::make('External Description')
->sortable()
->readonly(),
Text::make('External Type')
->sortable()
->readonly(),
]),
// Broken new Panel with Translatable fields
new Panel('Candidate Translations', [
Translatable::make([
Text::make('Candidate Description')
->sortable()
->hideFromIndex(),
]),
Translatable::make([
Text::make('Candidate Type')
->sortable()
->hideFromIndex(),
]),
]),
];
}
...
i was wondering if could be possible extending the package or if there is a know workaround to see the fields on tabs?
the package is awesome, but aving redundant fields just hurts eyes <3
i installed this package on nova for translations : https://github.com/spatie/nova-translatable
just that it shows me for example the articles in one language see them in all languages?
https://drive.google.com/file/d/1eYSYbooxesgs3n-x7mE9KXqUNBYHK4pA/view?usp=sharing
if the current language is Italian I see only the articles in Italian same thing for English but I can't see both articles in Italian and in English ... how could I do?
is there a way to make it work with KeyValue field ?
Hello,
I get an error when I try to delete a template that has a Trix field without an attachment:
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'nova_trix_attachments' does not exist
I think the error comes from this line:
https://github.com/spatie/nova-translatable/blob/3.x/src/Translatable.php#L254
By default attachments are disabled and this method force its activation ($this->withFiles = true;
)
By removing the withFiles()
I no longer get the error
private function createTrixUploadField(Trix $field, string $locale): Trix
{
return Trix::make('translations_' . $field->attribute . '_' . $locale)
/* ->withFiles(
$field->getStorageDisk(),
$field->getStorageDir()
) */
->hideFromIndex()
->hideWhenCreating()
->hideFromDetail()
->hideWhenUpdating();
}
Sincerely
TL-DR : I want to check uniqueness by locale for translatable fields but don't find how
I try to ensure that a user can only set unique value for a translatable field.
I've set up the field like this
Translatable::make([
Text::make('name')
->rules('required', 'string', 'unique:sports,name')
]),
Let's assume a simple Sport resource with only a translatable name. I create a first sport with those translations :
and then another one with the followings :
This only checks that the whole json is unique so the previous example the validation passes. What I want to accomplish is to check that the uniqueness is checked at the translation level so the validation should fail (because Football is already used in the first fr locale in the example). Is their a way to achieve that ?
Defining a Translatable field in a Page template's fields will result in this exception, for instance:
Argument 2 passed to Spatie\NovaTranslatable\Translatable::Spatie\NovaTranslatable{closure}() must be an instance of Illuminate\Database\Eloquent\Model, instance of App\Nova\Templates\Home given
@Nyratas mentioned that model classes shouldn't be type-hinted in function arguments "for scenarios like these."
When i try to drag and drop images into translatable trix field, i can see image is dropped but after i save it, i see nothing in db or upload directory. Basically it ignores dropped image after saving. I do not get any error or feedback. Everything seems went smooth but result is nothing saved.
Translatable::make([
Trix::make(__('Body'))
->withFiles('media')
->rules('required')
])->displayLocalizedNameUsing(function (Field $field, string $locale) {
return ucfirst($field->name) . "[{$locale}]";
}),
Anyone can confirm this behavior?
Looks like it doesn't work for a Repeatable field:
Laravel\Nova\Fields\Repeater\Repeatable::Laravel\Nova\Fields\Repeater\{closure}(): Argument #1 ($field) must be of type Laravel\Nova\Fields\Field, Spatie\NovaTranslatable\Translatable given, called in /var/www/html/vendor/laravel/framework/src/Illuminate/Collections/Traits/EnumeratesValues.php on line 240 {"userId":1,"exception":"[object] (TypeError(code: 0): Laravel\\Nova\\Fields\\Repeater\\Repeatable::Laravel\\Nova\\Fields\\Repeater\\{closure}(): Argument #1 ($field) must be of type Laravel\\Nova\\Fields\\Field, Spatie\\NovaTranslatable\\Translatable given, called in /var/www/html/vendor/laravel/framework/src/Illuminate/Collections/Traits/EnumeratesValues.php on line 240 at /var/www/html/vendor/laravel/nova/src/Fields/Repeater/Repeatable.php:99)
Hi,
Please add support for Nova 4.
Thanks for the awesome package.
Translatable
's fillUsing
callback explodes the whole attribute name (ie translatable_slug_en_US
at the underscores and the actual attribute ends up being slug_en
instead of slug
.
Nova Version: 4.8.1
Laravel Version: 9.17.0
spatie/nova-translatable: 3.1.1
When using this package in combination with nova tools like nova-settings (https://github.com/outl1ne/nova-settings) or Nova Command Runner (https://github.com/stepanenko3/nova-command-runner) the following method throws an error since there is no 'controller' index on those route actions:
vendor/spatie/nova-translatable/src/Translatable.php:233
protected function onIndexPage(): bool
{
if (! request()->route()) {
return false;
}
$currentController = Str::before(request()->route()->getAction()['controller'], '@'); // Throws an error here
return $currentController === ResourceIndexController::class;
}
I think we just need a null coalesce to fix this:
protected function onIndexPage(): bool
{
if (! request()->route()) {
return false;
}
$currentController = Str::before(request()->route()->getAction()['controller'] ?? '', '@');
return $currentController === ResourceIndexController::class;
}
Hello Freek,
I would like to ask for permission to maintain a Nova 3 compatible fork of this repo over at https://github.com/carandclassic/laravel-nova-translatable
Of course 99% of the repository would stay the same and Spatie would be credited.
Displaying the fields like that when having a lot of languages looking so ugly.
I think Tabs will look better and suits to everyone's project
https://github.com/mrmonat/nova-translatable like in this package
But problem with this package is it doesnt allow to use different field types ..
When trying to add Translatable fields into my Nova action fields
function, I keep getting the error:
Call to undefined method Spatie\\NovaTranslatable\\Translatable::resolveForAction()
Does this mean I can't add Translatable fields to Nova action fields?
When running my test-suite on PHP8.2 without deprecation handling, I get this error :
ErrorException: Creation of dynamic property Spatie\NovaTranslatable\Translatable::$translatedFieldsByLocale is deprecated in /path/to/project/vendor/spatie/nova-translatable/src/Translatable.php:173
Not sure what this property is used for, it looks like it is used only at this line...
We need an option to use different rules for each locale.
For example we might require one language (primary) but not all translations (nullable).
I have a nova field description and I used this package to translate the description to my supported locale in my app then when I type this sentence "We offer Aluminium Fence" and then create it, the sentence can't translate into de
It's just a suggestion for some who would like to enable sortable for translatable fields.
Could be added to the readme.
protected static function applyOrderings($query, array $orderings)
{
$model = static::newModel();
// this part is for default ordering by something else then by ['id' => 'desc']
if(empty($orderings) && property_exists(static::class, 'defaultOrderBy')){
$order = static::$defaultOrderBy;
$orderings = is_array($order) ? $order : [$order => 'asc'];
}
// this part check for translatable key and change them to fit with current locale
if (method_exists($model, 'isTranslatableAttribute')){
$locale = app()->getLocale();
$newOrderings = [];
foreach($orderings as $key => $order){
if($model->isTranslatableAttribute($key)){
$newOrderings[$key . '->' . $locale] = $order;
} else {
$newOrderings[$key] = $order;
}
}
$orderings = $newOrderings;
}
return parent::applyOrderings($query, $orderings);
}
Not working with Nova 4 Slug field
And I think with dependsOn doesn't working either
I have isolated the problem in a minimal Laravel/Nova installation. The basic installation is done with the following versions:
And the following Migration is used:
Schema::create('pages', function (Blueprint $table) {
$table->id();
$table->json('title');
$table->json('slug');
$table->json('body');
$table->timestamps();
});
and the following model:
class Page extends Model
{
use HasTranslations;
public $guarded = [];
public $translatable = ['slug', 'title', 'body'];
}
and the following Resource:
class Page extends Resource
{
/**
* The model the resource corresponds to.
*
* @var string
*/
public static $model = \App\Page::class;
/**
* The single value that should be used to represent the resource when being displayed.
*
* @var string
*/
public static $title = 'id';
/**
* The columns that should be searched.
*
* @var array
*/
public static $search = [
'id',
];
/**
* Get the fields displayed by the resource.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
public function fields(Request $request)
{
return [
ID::make()->sortable(),
Translatable::make([
Text::make('title'),
Text::make('slug'),
Trix::make('body'),
]),
];
}
/**
* Get the cards available for the request.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
public function cards(Request $request)
{
return [];
}
/**
* Get the filters available for the resource.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
public function filters(Request $request)
{
return [];
}
/**
* Get the lenses available for the resource.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
public function lenses(Request $request)
{
return [];
}
/**
* Get the actions available for the resource.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
public function actions(Request $request)
{
return [];
}
}
And the default locales:
\Spatie\NovaTranslatable\Translatable::defaultLocales(['en', 'ar']);
The problem is when creating one model with the the Resource form with values such as:
All the values are ignored and the last input value is what is used in all the other fields!
But if I use the Update form the values are stored fine.
It looks like a bug in the library. Because without Translatable the creating works fine.
Creation of dynamic property Spatie\NovaTranslatable\Translatable::$translatedFieldsByLocale is deprecated in [project]/vendor/spatie/nova-translatable/src/Translatable.php on line 173
I hope this package can be used with spatie/laravel-translation-loader.
Translatable::make([
Text::make('Text', 'text')
->rules([
'required',
]),
]),
Hi,
on a field Markdown with upload file allowed :
Translatable::make([
Markdown::make('Description')
->alwaysShow()
->withFiles('s3')
->rules(['required']),
]),
The url to the upload return a 404 as the end of the URI is for example : field-attachment/translations_description_en
Without translatable it works as the end of the URI is : field-attachment/description
How this can be solved ?
Best regards
Slug field loses functionality when using Translatable.
Translatable::make([
Text::make(__('Title'), 'title'),
Slug::make(__('Slug'), 'slug')->from(__('Title'))->separator('-')
]),
When I try to translate a Nova File Field I get error when saving. The File Field is trying to save the translations_FIELDNAME_LANG
attribute and not the FIELDNAME
attribute.
I don't really see through how nova-translatable
and the File Field are working so I have no idea what the best approach would be to fix this. If you have a hint I'd be happy to do a PR.
Hello,
when I use displayUsing callback on field, it returns wrong data.
Code:
Translatable::make([
Text::make('Title', 'title')
->displayUsing(function($translatedField, $model, $originalAttribute) //var1, var2, var3
{
dd($translatedField, $model, $originalAttribute);
}),
]);
When I am on detail page (resources/articles/some-id) it returns:
var1:
array:3 [
"title" => array:2 [
"cs" => "1111111111111111111111111"
"en" => "2222222222222222222222222222"
]
var2:
Article model {}
var3:
"translations"
When I am on index page, it returns right data:
var1:
"1111111111111111111111111"
var2:
Article model {}
var3:
"title"
Index page behaviour is okay. Is there way how to fix behaviour on detail page? Because with this data it's not possible to use it properly.
Thank you very much
Daniel
Nova 1.1.7
In index view.
Sorting on a translated field (column) only works in ascending order.
Second click, to toggle ascending/descending sorting, does nothing.
I want to use this package for translatable file but it is not working for file because fillusing function is not working for files is there any other method or way to use it for files please help me
Thanks
why the field does not work with CKEditor4 Field or Nova TinyMCE ?
just empty field
Translatable::make([
NovaTinyMCE::make('translatable_value'),
]),
but if i write
Translatable::make([
NovaTinyMCE::make('translatable_value_### fr'),
]),
The field will appear, but I will not be able to make changes, because I do not have such a field
The XHR error returned is 404
POST http://site.test/nova-api/posts/field/translations_content_ar/preview?editing=true&editMode=update
[HTTP/1.1 404 Not Found 230ms]
I works fine on non translatable fields like:
http://site.test/nova-api/news/field/intro/preview?editing=true&editMode=update
And returns 404 on a translatable field content
- the original query is (notice the transformed fieldname translations_content_en
):
http://site.test/nova-api/posts/field/translations_content_en/preview?editing=true&editMode=update
But I tested different URLs for this field - none works:
http://site.test/nova-api/posts/field/translations_content/preview?editing=true&editMode=update
http://site.test/nova-api/posts/field/content_en/preview?editing=true&editMode=update
http://site.test/nova-api/posts/field/content/preview?editing=true&editMode=update
Hi,
i've just installed a fresh version of nova-translatable (^3.0) and laravel-translatable (^4.4)
I've setup everything as documented. The Model has the Trait and the $translatable setup. When i use Text or Textarea in the Nova Resource everything is working fine when updating the values. But when i use Trix it doesn't throw any error and seems to save the resource just as fine but the values of the translateable field wont save. They stick to what they were before.
Hello
Thank you for your package , It's great.
But I have an issue in keyvalue field
I have field called seo and when i stored data on it you can see the result below:
{"en":"{"meta_title":" sdf sdf ","meta_description":" sdf sdf ","meta_keywords":" sdf sdf "}","ar":"{"meta_title":"tyrt","meta_description":"rty","meta_keywords":"uiu"}"}
I can't retrieve the data.
any advice please
Making multiple translatables on the same resource page automatically joins them into one continuous form even if you attempt to separate them using panels.
For example; The title and slug of this model is translatable. Though it also has an Seoable trait that adds SEO field to the model, these fields are also translated, though should be distinct from the native fields on the model.
public function fields(Request $request)
{
return [
$this->publishingFieldsPanel(),
Images::make('Featured Image', 'feature')->thumbnail('thumb'),
Translatable::make([
Text::make('title')->sortable(),
Text::make('slug')->rules('required', function ($attribute, $value, $fail) {
if (strpos($value, ' ') !== false) {
return $fail('The Slug cannot contain spaces, please add a \'-\' between each word.');
}
return $value;
}),
]),
new Panel('SEO Information', $this->seoFields()),
HasMany::make("Modules")
];
}
and this is the function that generates the SEO fields
public function seoFields()
{
return [
Translatable::make([
Text::make('SEO Title', 'seo_title')->hideFromIndex(),
Trix::make('SEO Description', 'seo_description')->hideFromIndex()
])
];
}
Note: i do not mean separating out locales but rather having multiple instances of Translatable per resource.
I'm not sure if that is intended functionality?
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.