I'm trying to translate paragraphs in Drupal 8. According to this bug report, which is marked as fixed, it should work.
#2543258: Entity references of untranslatable fields are not displayed in the correct translation is supposed to be fixed as well.
I don't know if this has anything to do with it. Right now, I'm stuck and I even don't know if this really should work or not.
I'm doing the following:
- In hook_preprocess_page there is $vars["node"] (as usual available via argument $vars)
- On this node (could in fact be any arbitrary Node object, I guess) I will call $node->getFields()
- One of the fields is a pararaph node ("field_sidepane")
- I call "$field->view()" on this field to render the whole field (i.e. everything that's in the sidepane) at once. view() doesn't seem to support a second argument for the langcode or anything.
- The sidepane contains multiple paragraphs (Cardinality=-1). One of these paragraphs contains a field "field_body" of type "text_long".
- This field is marked as translatable (under the Paragraphs section of the config page). field_sidepane by itself (appearing under the Content section of the config page), however, is not marked as translatable.
- Apart form the minor glitch, that these paragraphs are wrongly labeled as "All languages" (which I think is https://www.drupal.org/node/2463575) everything works great during edit-time. I can edit text separately for the different languages etc.
- On the page, however, only the primary language is ever shown.
I thought it would be straightforward but I turns out to be surprisingly difficult. In the class Drupal\Core\Entity\Entity\EntityViewDisplay I discovered the following section:
// The language of the field values to display is already determined
// in the incoming $entity. The formatter should build its output of
// those values using:
// - the entity language if the entity is translatable,
// - the current "content language" otherwise.
if ($entity instanceof TranslatableInterface && $entity->isTranslatable()) {
$view_langcode = $entity->language()->getId();
}
else {
$view_langcode = NULL;
}
I've found that if I set $view_langcode
to NULL
, it seems to work. Obviously, it gets the language from the main entity. But I don't know how I can change this in any way (either programmatically nor via the UI). Even if I explicitly use $node = $node->getTranslation("en");
and call getFields()
on the result, it doesn't seem to work. I could find no way whatsoever to render the field in the translated language.