Caching not properly working when using Tokens in Views

Created on 10 December 2021, almost 3 years ago
Updated 5 August 2023, over 1 year ago

Problem/Motivation

Caching is not working properly when using Tokens.

Within the ViewsTokenized::alterQuery method, the ViewsExecutable object can be retrieved and cacheability metadata can be attached like the following:

<?php
  public function alterQuery(AlterableInterface $query) {
    $to_replace = [];
    $view = $query->getMetaData('view');
    if (!($view instanceof ViewExecutable)) {
      return;
    }
    // ...
    foreach ($to_replace as &$text) {
      $text = trim($this->token->replace($text, $token_data, ['langcode' => $langcode], $bubbleable_metadata));
    }
    $bubbleable_metadata->applyTo($view->element);
    $bubbleable_metadata = BubbleableMetadata::createFromRenderArray($view->element);
?>

But that makes not really sense, because it runs after \Drupal\views\Plugin\views\cache\CachePluginBase::generateResultsKey() already generated a cache key, omitting important cache contexts as they are not known beforehand.

Steps to reproduce

Proposed resolution

Two workarounds to prevent caching conflicts:

  • Disable caching for the View (click on Caching: within Views UI display config and choose "None")
  • Add a contextual filter that would then automatically include the cache context beforehand. For example when using the node coming from the URL, then you need to add a contextual filter for it. You can do so by choosing "Global: Null" within contextual filters,
    and then select "Provide a default value" -> "Content ID from URL".

The Context Stack module might be able to solve this situation in the future by introducing cache contexts for entities. Related issue: #3253876: Provide cache contexts for entities and other objects

Remaining tasks

User interface changes

API changes

Data model changes

🐛 Bug report
Status

Closed: won't fix

Version

1.0

Component

Code

Created by

🇩🇪Germany mxh Offenburg

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Comments & Activities

Not all content is available!

It's likely this issue predates Contrib.social: some issue and comment data are missing.

Production build 0.71.5 2024