4

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.

9

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.

3
  • The return code has a syntax error. Dont know how this worked for you. Although the answer below plus the "\Drupal::service('page_cache_kill_switch')->trigger();" line solved the issue for me
    – ventura
    Oct 9 '21 at 12:04
  • @ventura, you can't just copy-and-paste this return statement. You only need this code in the context of the question.
    – 4k4
    Oct 9 '21 at 12:30
  • Fair enough. Regardless, I thought my comment might help someone :) No offence intended
    – ventura
    Oct 14 '21 at 12:27
8

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'
3
  • Works only if your route doesn't require a TrustedRedirectResponse Aug 29 '19 at 14:45
  • 1
    @ChristopheCARON could you give a bit more information on this? I tested it with a TrustedRedirectResponse and seems to do the job.
    – kufeiko
    Nov 26 '19 at 11:00
  • This seems like the best (and simplest) answer. My controller is redirecting based on the site language and using TrustedRedirectResponse to an external URL. The no_cache option works well. Jul 21 '21 at 17:40

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.