Is there any option to have multilingual predefined / default content for structure fields?
Hey @jakobgrommas I guess you have already tried this without success?
No, I don’t think it is possible. You could use a workaround though by defining a set of translations in the blueprint and add these to the language variations via a hook.
Hey, thank you for your fast response. Should I take the page.create:after
hook for that? Do you have more specific hints on how to define the translations in the blueprint? I already tried it with the multilingual syntax, but that’s just displaying an array as a default text.
Yes.
Let’s assume you have a simple structuure field like this:
fields:
testfield:
label: My testfield
type: structure
translations:
blue:
de: blau
green:
de: grün
default:
- text: blue
- text: green
fields:
text:
label: Text
type: text
As you can see, I have added a translations property with translated values for each of the stored values. Note that this is just a custom added property (you can name if whatever you want).
You can now fetch the array of values from the translations property like this:
dump($page->blueprint()->fields()['testfield']['translations']);
and take it from there.
The above gives you the following array
Array
(
[blue] => Array
(
[de] => blau
)
[green] => Array
(
[de] => grün
)
)
Thanks again! Still unsure how to solve it. After page creation I only have the default language. Do I have to trigger the creation of my second language or will that happen automatically? How can I then find the content to translate and how do I do that?
(I don’t have much experience in multilingual manipulations like that, so sorry for fooling around.)
Ok, we have to change the translation property a bit:
fields:
testfield:
label: My testfield
type: structure
translations:
de:
- text: blau
- text: grün
- text: rot
default:
- text: blue
- text: green
- text: red
fields:
text:
label: Text
type: text
Then you can do this in your hook in config:
'hooks' => [
'page.create:after' => function($page) {
// we check for the intended template, because we don't won't to do this anywhere
// adapt conditions as needed
if ($page->intendedTemplate()->name() === 'album') {
// we fetch our language specific defaults from the blueprint
$langDefaults = $page->blueprint()->fields()['testfield']['translations'];
// we loop through all languages except the default language
foreach (kirby()->languages()->not(kirby()->defaultLanguage()) as $language) {
// then we update each language translation with the language defaults by
// fetching them via the language key
$page->update([
'testfield' => yaml::encode($langDefaults[$language->code()])
], $language->code());
}
}
}
]
It works, thank you so much!!