Search code examples
shopwareshopware6

How can I create an entity with a translatable snippet as name


I want to create a new customer group in a plugin. The name of this customer group should be translatable. How can I achieve this? Here is my code until now:

$customerGroupRepository->create([
            [
                'id' => Uuid::randomHex(),
                'registrationActive' => false,
                'displayGross' => true,
                'translations' => [
                    Defaults::LANGUAGE_SYSTEM => [
                        'name' => 'Customer group',
                    ],
                    'de_DE' => [
                        'name' => 'Kundengruppe',
                    ],
                    'en_GB' => [
                        'name' => 'Customer group',
                    ]
                ]
            ],
        ], $context);

But this doesn't work. The name of the customer group is allways 'Customer group' no matter which language I choose in the shopware backend.


Solution

  • The locales need to include hyphens: de-DE, en-GB

    Using the correct locale they should be resolved to a language.id.

    Generally speaking it wouldn't be a bad idea though to first fetch the id of the language entities and then use them as the key instead. Just as a precaution to make sure the language/locale exists.

    With language.id:

    [
        // ...
        'translations' => [
            Defaults::LANGUAGE_SYSTEM => [
                'name' => 'Customer group',
            ],
            '9e4f6342174749aa897c5b64d57d7996' => [
                'name' => 'Kundengruppe',
            ],
            '0a7f24f26e48436d9f3b343fc43b65b7' => [
                'name' => 'Customer group',
            ]
        ]
    ]
    

    With locale:

    [
        // ...
        'translations' => [
            Defaults::LANGUAGE_SYSTEM => [
                'name' => 'Customer group',
            ],
            'de-DE' => [
                'name' => 'Kundengruppe',
            ],
            'en-GB' => [
                'name' => 'Customer group',
            ]
        ]
    ]
    

    Should both work.