Structure fields default values in multilingual setup

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());
                    }
                 }
            }
        ]
2 Likes