I created a structure from an array like this:
$fields['mail'] = [
'type' => 'email',
'label' => [
'en' => 'Mail Address',
'de' => 'Mail Adresse'
]
];
$fields['bla'] = [
'label' => 'Not Translated Bla'
]
$s = new Structure($fields);
Now I’m trying to run map, check if label is an array and try to select the right language key, if present and replace label with the translated string :
$s = $s->map(function($field){
$field->label = // set label to string with the right translation, or the fallback
return $field;
});
dump($s->toArray());
For one, I can’t set the label. $field->label = 'test' and then I’m not sure how to approach the translation the best. I checked the kirby source and how I18n::translate works, but it didn’t click. Any help would be appreciated! Thanks
PS: I guess I don’t have to use new Structure and just use the $fields array, but I want to understand the Kirby way of doing it.
Since the properties are protected, you cannot modify them.
So is there another way to solve this?
In general I want to learn how to use Kirby’s methods to do these kind of things (else I would use laravels collect() to manipulate an array)
The specific use case is to turn the example array above into a structure, maybe filter it, manipulate it and translate one property (that’s the example with ->map().
I guess using the example above, I want to turn this:
$fields['mail'] = [
'type' => 'email',
'label' => [
'en' => 'Mail Address',
'de' => 'Mail Adresse'
]
];
$fields['bla'] = [
'label' => 'Not Translated Bla'
]
to this:
$fields['mail'] = [
'type' => 'email',
'label' => 'Mail Adresse'
];
$fields['bla'] = [
'label' => 'Not Translated Bla'
]
using Kirby’s Collection/Structure and I18n Methods and Helpers.
(Hope that makes sense :))
If you use a collection instead of a structure, you can do it like this:
$s = new Kirby\Cms\Collection($fields);
$s = $s->map(function($field) {
$field['label'] = 'test';
return $field;
});
Thank you so much! This worked!
$fields['mail'] = [
'type' => 'email',
'label' => [
'en' => 'Mail Address',
'de' => 'Mail Adresse'
]
];
$fields['bla'] = [
'label' => 'Not Translated Bla'
]
$s = new Kirby\Cms\Collection($fields);
$s = $s->map(function($field) {
$field['label'] = I18n::translate($field['label'],$field['label']);
return $field;
});
Two things that I noticed:
-
Collection turns an associative array into an indexed one (you are losing the named array keys when converting back (unless I overlooked something)
-
the I18n::translate method takes an array with the language code as keys as in the above example with label. https://getkirby.com/docs/reference/tools/i18n/translate