Drupal Core's "Config Translation" module allows translating configuration values. Getting a configuration value in a certain language shouldn't be too hard, right?
I thought the same, but I was wrong, it's hard, if you don't know the required pattern.
I don't want to make this story too long, but what I wanted to achieve was just to send an email in the users language.
The email text was a configuration value and it was translatable.
What I expected to exist was:
- A helper method like
->getTranslated($id)
- An optional $langcode parameter in the
$config->get($id, $langcode = NULL)
function
but both don't exist, neither documentation seems to exist. But Drupal Core's code gave the answer, after I remembered where this also must be implemented.
The ConfigOverrideLanguage pattern
Drupal uses the following pattern to temporarily switch the language around getting values from config:
$original_language = $this->languageManager->getConfigOverrideLanguage();
$this->languageManager->setConfigOverrideLanguage(new Language(['id' => $langcode]));
// GET THE CONFIG VALUE HERE
$this->languageManager->setConfigOverrideLanguage($original_language);
That's not bad, because this way you don't need to pass $langcode parameters all through the code, but it's also not very self-explaining and very complex, if you just want a config value in a certain language.
So I opened the following Drupal Core DX issue to improve this: https://www.drupal.org/project/drupal/issues/3502608
Looking for a solution, I also found this contrib module, but didn't want to add a dependency just for this, so I decided against it. Also I think the contrib module has a different focus: https://www.drupal.org/project/translated_config
I hope, once again, that this blog entry will save many of you (and maybe myself) in the future. If it saved you time, please buy me a coffee. :)
(Or spend some of your time helping to improve the Drupal Core implementation!)