Drupal - Manage config translations programmatically
The answer from @Smartsheet eng is correct if you want to load and read a specific translation as a config entity, see also How to progragrammatically get NodeType translated value in D8?.
However, changing them is different, because the config entity can't be saved like that, it doesn't understand what is a translation and what's not. It will just overwrite your default language with that data. See also https://www.drupal.org/project/drupal/issues/2910353.
To actually manage a translation of a config entity, you have to directly interact with the config system, you can see how in \Drupal\config_translation\Form\ConfigTranslationFormBase::submitForm():
$config_translation = \Drupal::languageManager()->getLanguageConfigOverride($langcode, $config_name);
// Write the keys you want to translate on the config object.
$config_translation->save();
As far as I can see -- yes, this is possible but it's not as pretty as $contentEntity->getTranslation($langcode);
. The full enchillada would be:
protected function getTranslatedConfigEntity(ConfigEntityInterface $configEntity, LanguageInterface $language) {
$langcode = $language->id():
/** @var \Drupal\Core\Config\Entity\ConfigEntityTypeInterface $configEntityType */
$configEntityType = $configEntity->getEntityType();
$name = $configEntityType->getConfigPrefix() . '.' . $configEntity->id();
$translatedConfig = $this->languageManager->getLanguageConfigOverride($langcode, $name);
$translatedConfig[$configEntity->getKeys('langcode')] = $langcode;
$class = $configEntityType->getClass();
return new $class($translatedConfig->get(), $configEntityType->id());
}
An alternative would be:
public function getTranslatedConfigEntity(ConfigEntityInterface $configEntity, LanguageInterface $language) {
$currentLanguage = $this->languageManager->getConfigOverrideLanguage();
$this->languageManager->setConfigOverrideLanguage($language);
$translatedConfigEntity = $this->entityTypeManager
->getStorage($configEntity->getEntityTypeId())
->load($configEntity->id());
$this->languageManager->setConfigOverrideLanguage($currentLanguage);
return $translatedConfigEntity;
}