I have a Paragraph setup that has an entity reference field allowing an editor to select multiple nodes to use in a display.
Based on the count of nodes, I want to trigger a class. I figured a way to do this was with hook_preprocess_node()
in the theme:
$referringItem = $node->_referringItem;
if (!empty($referringItem)) {
$referringEntity = $referringItem->getEntity();
if (
!empty($referringEntity)
&& ($referringEntity instanceof NodeInterface || $referringEntity instanceof Paragraph)
) {
$referringEntityType = $referringEntity->getType();
$referringEntityTypeId = $referringEntity->getEntityTypeId();
}
}
if ($referringEntityType == 'homepage_feature') {
$count = $referringEntity->get('field_items')->count();
// Default.
$variables['top_image'] = FALSE;
$variables['right_image'] = FALSE;
// Should this be count is only 1 AND it is the first delta item in field_feature?
// If not, any single item Homepage Feature will get top-image which may not be
// desired.
if ($count == 1) {
$variables['top_image'] = TRUE;
}
}
The logic above might be too involved. Basically I am looking back to see what paragraph type was used, so I can pass new variables to the template.
What I noticed is that even though the code is hit for every node listed, the variables only exist in the first node. I dumped them in the template and it is correct there, but they are undefined in the other nodes.
In Twig, I tried dumping the variable at the top of the template:
{{ top_image }}
I can see it in the first record 1
above the markup, and then it never shows again.
How can I ensure the variables are passed to the template, correctly, every time?
Edit:
Looks like using the same node with the same view mode in different paragraphs or entity references on the same page can cause this to happen.
Is the solution then to add cache tags/context to the node being rendered to account for what parent is outputting it?
_referringItem
being present in preprocess, because this is added by the field formatter for internal use and when the node is rendered you might have a new instance of the node object. A solution might be extending the field formatter, add the information you want to the build array of the field elements and add cache keys (tags/context won't help in this case and you need to add the cache keys in the field formatter, preprocess is too late).