1

I have an address field from which I'm getting a country code and then, using the address.country_repository service, checking the country's name.

$full_country_list = \Drupal::service('address.country_repository')->getList();
$country_code = $user->field_nationality->first()->get("country_code")->getValue();
$result['nationality'] = t($full_country_list[$country_code], [], ['langcode'=>$user->get('langcode')->value]);

This repository returns a list with the country names translated in Drupal's default language (in my case, portuguese), but I'm trying to t()-function it to translate the string into other languages.

The t() function doesn't cut it, even if I pass the langcode option.

How can I get a translated version of the list so that I don't have to translate the string with t()?

1
  • getList() has a locale argument, try passing in your locale that you want to have it translated to. not sure if it's the same string as t() receives, the documentation mentions 'fr-FR' as example I think.
    – Berdir
    Mar 17, 2017 at 13:55

1 Answer 1

1

The country name in the country list is already a translatable markup object. It's not possible to add new options to it. So your idea to translate the country name again, this time with a specific langcode in options, is right. But you have to get the untranslated string if you want to translate it again

t($full_country_list[$country_code]->getUntranslatedString(), [], ['langcode' => 'de'])

because how you do it you get the translated string when running the code in a non english language context and translating from a non english language is not supported.


Edit: this answer is valid for the core country list

$full_country_list = \Drupal::service('country_manager')->getList();

there are probably other versions in contrib, see comment from @Berdir.

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.