I have a module with a custom entity (sample) and a
hook_preprocess_sample(). I have another custom entity (retain) that has an entity reference to sample. The preprocess hook looks in the database for any retain entities that reference the current sample, and adds it to the render array. This way I can link to the retain from the sample entity canonical page. The twig template checks if the render array has a retain. If yes, it links to its canonical route, if not, it links to the add-form route.
I have a third entity, (batch) which also has an entity references to sample entities. When the batch is rendered, all samples are rendered in a list. However, the rendered samples always have a link to “add a retain”, regardless of whether a retain exists or not. It looks like this is because
hook_preprocess_sample() is not invoked when the inner elements are being rendered.
How do I get the sub-elements within my batch Entity to render the way I want? I imagine I will need to make a preprocess function for my batch and have a foreach loop theme each sample, but maybe there’s a better, more convenient way. The curious part is the custom twig template IS being used for the samples in both cases, it’s just that the preprocess function is not running when the sample is an element of another entity.