1

We have enabled English, Spanish, and French on our site. On Regional and language >> Languages detection we selected URL for Content language detection >> Detection Method. For Part of the URL that determines language, we selected Domain. We then set the following domains.

  • English: example.com
  • Spanish: es.example.com
  • French: fr.example.com

How can we programmatically obtain the domain associated to each language? What code should we use in a preprocess function? Using the following code, we obtained the list of the language, but we are far from getting the domain that has been associated with each language.

function mymodule_preprocess_html(&$variables) {
  // to get all enabled languages
  $languages = \Drupal::languageManager()->getLanguages();

  // Did not find method to retrieve the domain configuration.
  foreach($languages as $key => $value) {
    ksm($languages[$key]);
    //stuck here on how to get domain configuration per language.
  }
}
0

The domain associated with each language is stored as configuration. Using the following code, $prefix will contain the prefix, and $domain the domain used.

  $config = \Drupal::configFactory()->get('language.negotiation');
  $languages = \Drupal::languageManager()->getLanguages();
  $prefixes = $config->get('url.prefixes');
  $domains = $config->get('url.domains');
  foreach ($languages as $langcode => $language) {
    $prefix = $prefixes[$langcode];
    $domain = $domains[$langcode];
  }

I wrote the code basing on NegotiationUrlForm::buildForm(), which is the form builder for the form that sets the negotiation URL for each language.

  • that got me exactly what i needed using the $config = \Drupal::configFactory()->get('language.negotiation'); – usernameabc May 20 at 16:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.