1

I have a route with a parameter, e.g. /r/{app_id}. The controller extends ContainerInjectionInterface. The method either returns a render array or a new TrustedRedirectResponse.

I believe I have a caching problem because subsequent visits to the page will not update even with changing {app_id}. If I visit from another browser I get the correct response one time.

My controller is, basically, this:

if (!$a) {
  return ['#markup' => 'no'];
}

return new TrustedRedirectResponse($url);

I have tried to disable cache in several ways, to no avail:

  • addCacheableDependency
  • putting #cache => ['max-age' => 0] on the render array
  • \Drupal::service('page_cache_kill_switch')->trigger();
  • using $response = new Response() and $response->setCache(['max_age' => 0]) and then, from within the conditional, using $response->setContent('blah')

Not having luck with any of the above.

5

You have to do all together, set cache max-age = 0 for all responses the controller returns and apply the kill switch

public function mycontroller() {

  \Drupal::service('page_cache_kill_switch')->trigger();

  if (!$a) {
    return [
      '#markup' => 'no',
      '#cache' => ['max-age' => 0],
    ];
  }

  return (new TrustedRedirectResponse($url))
    ->addCacheableDependency((new CacheableMetadata())->setCacheMaxAge(0));
}

and then clear the cache one more time.

0

You can also disable caching via the route under the options key like this, no_cache: 'TRUE'. Here is a full example of a route:

my_awesome_module.do
  path: '/do-awesome'
  defaults:
    _controller: '\Drupal\my_awesome_module\Controller\MyAwesomeModuleController::doAwesome'
  options:
    no_cache: 'TRUE'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.