i18n strings in database from yml files

Silverstripe Version: 4.10

What’s the best way of storing i18n strings from lang/xx.yml in a database?

I am looking for a solution for transferring the strings collected by the i18nTextCollector task in database and provide access to the content editors via the administration panel so they would be able to freely edit them.
Has anyone figured a way to do it or has any suggestions on how to implement this myself? I didn’t find relevant info

Thank you,

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:

  1. In your project’s mysite directory, create a new file called Translation.php.
  2. 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.