Search code examples
pluginsshopwareshopware6

Access translator in Shopware 6 Plugin


I am developing my first Shopware 6 plugin and was wondering how to access snippets in the Plugin class. I checked the Developer Guide but could not make it work.
I want to use the plugin translation as label in customField select options.

myfirstplugin.en-GB.json

{
    "myfirstplugin": {
        "my_custom_field_option_1": "Option 1",
        "my_custom_field_option_2": "Option 2",
    }
}

MyFirstPlugin.php

class MyFirstPlugin extends Plugin
{
// ....

    private function createCustomFields(Context $context): void
    {
        if ($this->customFieldSetExists($context)) {
            return;
        }

        $customFieldSetRepository = $this->container->get('custom_field_set.repository');
        $customFieldSetRepository->create([
            [
                'id' => '294865e5c81b434d8349db9ea6b4e135',
                'name' => 'my_custom_field_set',
                'customFields' => [
                    [
                        'name' => 'my_custom_field',
                        'type' => CustomFieldTypes::SELECT,
                        'config' => [
                            'label' => [ 'en-GB' => 'My custom field'],
                            'options' => [
                                [
                                    'value' => '294865e5c81b434d8349db9ea6b4e487',
                                    // Access my_custom_field_option_1 of snippet myfirstplugin.en-GB.json 
                                    'label' => 'my_custom_field_option_1', 
                                ],
                                [
                                    'value' => '1ce5abe719a04346930c7e43514ed4f1',
                                    // Access my_custom_field_option_2 of snippet myfirstplugin.en-GB.json 
                                    'label' => 'my_custom_field_option_2',
                                ],
                            ],
                            'customFieldType' => 'select',
                            'componentName' => 'sw-single-select',
                            'customFieldPosition' => 1,
                        ],
                    ],
                ]
            ],
        ], $context);
    }

}

Solution

  • You can inject an argument of type Translator to your service

    in services.xml

    <argument type="service" id="translator"/>
    

    in your service

    use Shopware\Core\Framework\Adapter\Translation\Translator;
    
    /**
     * @var Translator
     */
    private $translator;
    public function __construct($translator)
    {
        $this->translator = $translator;
    }
    

    then down the way you can use this pretty much the same as in a twig template:

    $translated = $this->translator
        ->trans(
             'myfirstplugin.product.detail.294865e5c81b434d8349db9ea6b4e487');