How do I filter entity reference fields based on language? In a Drupal 8 site I have a node content type "page" that references a custom entity type using inline entity form. "Page" also has a paragraphs field usig the Paragraphs module.

The site have multiple languages and therefore the following scenario appears:


I have an existing "page" node in both english and german containing entity references and paragraphs.
On the english node I add a new paragraph and a new entity reference and save the node.
When viewing the node in english I see the  added content.
When viewing the node in german I also see the new content, which is in english.


I don't want number 4 to happen. That is, I don't want the new untranslated entity and paragraph to be visible on the german translation of the node. The entity reference and paragraph fields are not set as translatable but the target entities are translatable. From what I understand, this means that the newly created entity will be in english, the same is true for the paragraph.

To solve this I'm thinking I should be able to filter out the untranslated entities and paragraph items when viewing the node so that any item that is not in the current language is not shown. The they won't be visible until I go and edit the german node and resave it, which will create translated versions of the entity and paragraph item.

But I am unsure how to go about filtering the fields. Is there any suitable hook that can be used? Or am I going about this in the wrong way?
The logic that defines if entities should be shown is in \Drupal\Core\Field\Plugin\Field\FieldFormatter\EntityReferenceFormatterBase::getEntitiesToView()

As you can see, translation is checked there, but the API doesn't directly support skipping something, the hooks behind that only allow to control applicable fallback languages and their order.

It's possible that you can use entity access, which is checked after that. Implement hook_paragraph_access(), for the view operation, check if the paragraph has a translation in the current content language and if not, forbid access. The same should work for your other entity reference, it's the same could, just implement hook_ENTITY_TYPE_access() for that too.

If that doesn't work, you can write your own field formatter plugin and override that method.