3

In a module (not a template), I need the label of a specific field in multiple languages.

$entity->getFieldDefinition('myField')->label() gives me the label in current/active language (let's say, English).

What doesn't work as expected is the following:

$entity->getTranslation('fr')->getFieldDefinition('myField')->label()

I would expect the label in French. Instead, I get the label English. How to get the French label?

4

You can load an entity's translation by using the entity repository service. The field configuration is an entity itself. So you could try this:

use Drupal\field\Entity\FieldConfig;

// Override language before loading field configuration.
$language = \Drupal::languageManager()->getLanguage('fr');
\Drupal::languageManager()->setConfigOverrideLanguage($langu‌​age);

// $entity_type, $bundle, $field.
$field_info = FieldConfig::loadByName('entity_type', 'bundle', 'myField'); 

$label = $field_info->getLabel();

EDIT:

As stated by 4k4 within the comments, config entities don't behave like content entities. So in order to get their translations, you will need to override the language before getting their translatable strings. Adjusted the example accordingly.

  • Thanks, but unfortunately this doesn't work. I still get the label in English. There must be some way to get it.... – user125661 Dec 10 '17 at 4:13
  • 2
    This is a good idea, loading the config entity, but you can't translate it like content. Override the config language before loading FieldConfig: $language = \Drupal::languageManager()->getLanguage('fr'); \Drupal::languageManager()->setConfigOverrideLanguage($language); – 4k4 Dec 10 '17 at 15:47
  • Would have been my next guess, as the docs state getLabel() returns a string or a translatable. I'll update my answer accordingly. – Mario Steinitz Dec 10 '17 at 22:48

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.