Winter CMS resources and help articles

Simple and to the point. Optimized by the community.

Translate settings model

0
by Dreanad, last modified on August 5th, 2023

Your settings model need to implement "Winter.Translate.Behaviors.TranslatableModel"

        $settings        = YourSettingsModel::instance();
        $translator     = Translator::instance();
        $original         = $settings->toArray();
        $translated    = $settings->getTranslateAttributes($translator->getLocale()); // Only translated attributes, no data if lang has none

If you need to keeps original data if lang is missing :

        $settings        = $this->mergeAssociativeArrays($original, $translated); // keeps original data if lang is missing  

/**
     * Merge two associative arrays recursively, replacing values of the first
     * array with the values of the second array.
     *
     * @param array $array1
     * @param array $array2
     * @return array
     */
    private function mergeAssociativeArrays($array1, $array2) {
        foreach ($array1 as $key => $value) {
            if (isset($array2[$key]) && $array2[$key] !== '') {
                if (is_array($value) && is_array($array2[$key])) {
                    $array1[$key] = self::mergeAssociativeArrays($array1[$key], $array2[$key]);
                } else {
                    $array1[$key] = $array2[$key];
                }
            }
        }
        return $array1;
    }

Discussion

0 comments

We use cookies to measure the performance of this website. Do you want to accept these cookies?