Search code examples
shopware

How to get localized CMS Element config data in controller of shopware6


I have the following situation. I have a custom CMS-Element with a form in it, I send the data via a AJAX in a written JS-Plugin to a custom controller. Now I would like to read informations from the CMS-Element Config. I peeked inside the Source of the Contact-Form and ended in their controller where they read out the configuration. I implemented it in my controller and basicly it worked but the only thing that isn’t working is that I always get the config of one Language (German). My Primary language is English and my secondary is German.

I took the “Dailymotion” example from the guides. And added melted it with the code from the other guide for AJAX calls. (For testing purpose)

https://developer.shopware.com/docs/guides/plugins/plugins/content/cms/add-cms-element https://developer.shopware.com/docs/guides/plugins/plugins/storefront/add-dynamic-content-via-ajax-calls

In the source of the ContactForm (ContactFormRoute.php) are the lines with

$mailConfigs['receivers'] = $slot->getEntities()->first()->getTranslated()['config']['mailReceiver']['value'];

https://github.com/shopware/platform/blob/d6c853ca3b6b167d61d70e6329f4fcface5c5245/src/Core/Content/ContactForm/SalesChannel/ContactFormRoute.php#L182

I’ve added the same but I only get the secondary language config data. I modified the code that he get the dailyUrl value from the config.

What I noticed is that in my $context the languageIdChain contains both language IDs (the first one is the German one) in the contact thereis only the languageId of the current language:

These are the languageIdChain of the Context sended in the English language. (2fbb5fe2e29a4d70aa5854ce7ce3e20b is the English Language)

Context languageIdChain of the Contact form controller:

  #languageIdChain: array:1 [
    0 => "2fbb5fe2e29a4d70aa5854ce7ce3e20b"
  ]

Context languageIdChain of my controller:

  #languageIdChain: array:2 [
    0 => "2d7d7d698f634a04b5796e49aa846ae6"
    1 => "2fbb5fe2e29a4d70aa5854ce7ce3e20b"
  ]

Solution

  • Ok, you know the moments where you struggle many hours, try this and that and then do the Stack Overflow post an after a half hour you find the solution yourself.

    The reason why I always get the German data instead the data of the current Language is that my AJAX call simply calls always the route for the German language /example like in the Guide shown. Instead using a hard coded URL in the JS-Plugin I updated the template

    <button id="ajax-button" data-url="{{path('frontend.example.example.submit')}}">Button</button>
    

    And in my JS-Plugin I just read out the data-url

    this.button = this.el.children['ajax-button'];
    this.actionUrl = this.button.dataset.url;
    

    This ways I get the url /example or /en/example depending on the current language.