问题
I have added the Translate behaviour and everything works fine, I can switch to any language etc. The only thing that isn't working is when I switch to the same language as the one which is set in app.php as defaultLocale:
'App' => [
...
'defaultLocale' => env('APP_DEFAULT_LOCALE', 'en_US'),
...
],
I don't get the translated fields.
When I remove the 'defaultLocale' setting it works fine for all languages.
Can someone tell me what is going wrong here?
@ndm Thanks, that was very helpful. However now I run into another problem. That's how to make the multi language input form? So I have 4 languages (locales): en_US, nl_BE, fr_BE, de_BE and ru_RU. The defaultLocale is en_US. So to ADD a new record I did:
// for the defaultLocale
echo $this->Form->control('title');
// for all other languages I iterate over every language except of the defaultLocale
foreach ($supported_locales as $key => $val):
if ($key !== $default_locale):
echo $this->Form->control('_translations.' . $key . '.title');
endif;
endforeach;
This works fine. Allthough I'm not sure if this is the proper Cake-way to do it?
But in the VIEW (using a disabled form) and EDIT the defaultLocale field
echo $this->Form->control('title');
shows the translated value of the selected locale at that moment instead of the defaultLocale which is saved in the source table. F.e. when you switched the language to Russian at that moment you'll get to see:
English: Русский титул Dutch: Nederlandse titel French: Titre français Deutsch: Deutscher Titel Russian: Русский титул
So you're missing the value for the default locale.
Am I overlooking something and is there a easier way to make this work 'out of the box'?
回答1:
That's by design, the translate behavior expects that the content for the default locale is present in the source table, not the translation table. This is similar to using translation functions and language files, the function calls (the source table) contain the default locale messages, and the language files (the translation table) contain the localized messages.
Quote from the docs:
The philosophy behind the TranslateBehavior is that you have an entity representing the default language, and multiple translations that can override certain fields in such entity. [...]
So the behavior works that way in order to be able to preserve non-overriden fields, say if your source table has title
and content
fields, and there's only a translation for the content
field in the fr_FR
locale, then title
will contain the untranslated (default locale) content when querying the record for the fr_FR
locale.
See also
- Cookbook > Database Access & ORM > Behaviors > Translate
来源:https://stackoverflow.com/questions/52000517/cakephp-3-6-10-translate-behaviour-not-showing-defaultlocale-values