I have a situation where two Paragraphs on single page may potentially reference the same entity.
The affected paragraphs have a field to change their colour, and this colour value is passed down to the referenced entity (via hook_preprocess_[entity-type]) for use in its template.
Node
field_paragraph
Paragraph1
- field_colour
- field_entity_reference (references entity:1234)
Paragraph2
- field_colour
- field_entity_reference (references entity:1234)
When I update Paragraph 1 to change its colour, this is currently affecting the colour of Paragraph 2 (because the entity is cached, including the colour value that is preprocessed into it).
I have tried adding a cacheable dependency (in hook_preprocess_[entity-type]) to transfer the cache tags for the paragraph to the entity, so that when the paragraph is updated, it invalidates the cache for the entity it is referencing:
$renderer = \Drupal::service('renderer');
$renderer->addCacheableDependency($variables, $referring_entity);
I have also tried replacing $variables
in the above with $variables['elements']
and $variables['content']
, but either way this does not seem to work as I expected.
Any advice appreciated.