1

Fields definition in Drupal 9 can be translated: field label, field description and default value(s) can get per-language values.

In a hook_form_alter I need to "copy" some existing fields, but with a different language. My process is:

// force wanted language
$language_manager->setConfigOverrideLanguage($target_language);
\Drupal::service("entity_field.manager")->clearCachedFieldDefinitions();
// getTranslation or addTranslation to the $entity depending on the case
if ($entity->hasTranslation($langcode)) {
  $entity = $entity->getTranslation($langcode);
} else {
  $entity = $entity->addTranslation($langcode);
}
// get the field
$field_definition = \Drupal\field\Entity\FieldConfig::loadByName($entity_type, $bundle, $field_name);
$form_display = EntityFormDisplay::collectRenderDisplay($entity, 'default');
$items = $entity->get($field_name);
$widget = $form_display->getRenderer($field_name);
$field_form = $widget->form($items, $form, $form_state);
// + restore initial language
// insert field in my $form
$form['my-added-field-name'] = $field_form;

This works fine for the label and the description of the field (they are translated in the target language). But it fails for the default value (in case of node creation rather than modification). Well, it works sometimes, but not always, and not in all cases. For example if I create new content in a language which is not the default one the default value is not translated and always the one of the current language.

I tried many things, such as using setLangcode() on $items, performing multiples $entity->getTranslation(), etc. Looking at the data, it seems that the $widget is in the good language (the one I forced) but that $items still has current language in it (even after using setLangcode() on it). And so after calling $widget->form() I get bad results (or, at least, non stable results).

So, did I miss something? Is there an other/better way to do this? Regards.

baikho
  • 5,203
  • 4
  • 40
  • 47
hexasoft
  • 677
  • 3
  • 9

0 Answers0