The best way to store i18n strings from lang/xx.yml in a database would be to use the Silverstripe SiteTree class and the SiteTreeExtension class to create a new Translation data object.
Here’s an example of how you could do this:
- In your project’s
mysite directory, create a new file called Translation.php.
- In
Translation.php, add the following code:
<?php
use SilverStripe\ORM\DataObject;
class Translation extends DataObject
{
private static $db = [
'Language' => 'Varchar(2)',
'Original' => 'Varchar(255)',
'Translation' => 'Text',
];
private static $has_one = [
'Page' => 'SilverStripe\CMS\Model\SiteTree',
];
}
This code creates a new Translation data object with three fields: Language, Original, and Translation. It also has a has_one relation to the SiteTree class, which allows it to be associated with a specific page on the site.
Next, you will need to create a new SiteTreeExtension class to handle the translation of the i18n strings. In your mysite directory, create a new file called SiteTreeExtension.php and add the following code:
<?php
use SilverStripe\ORM\DataExtension;
use SilverStripe\i18n\i18n;
class SiteTreeExtension extends DataExtension
{
public function updateCMSFields(FieldList $fields)
{
// Get the current language
$lang = i18n::get_locale();
// Get the translations for this page
$translations = Translation::get()->filter(['PageID' => $this->owner->ID, 'Language' => $lang]);
// Loop through the translations and update the field values
foreach ($translations as $translation) {
$fields->dataFieldByName($translation->Original)->setValue($translation->Translation);
}
}
}
This code will loop through all of the translations for the current page and language, and update the corresponding fields with the translated values.
Finally, you will need to apply the SiteTreeExtension to the SiteTree class in your YAML configuration. In the mysite/config directory, create a new file called extensions.yml and add the following code:
SilverStripe\CMS\Model\SiteTree:
extensions:
- SiteTreeExtension
This will apply the SiteTreeExtension to the SiteTree class, allowing the translations to be stored in the database and displayed on the site.
You can then use the Silverstripe CMS to create and manage the translations for your site.