3

I have a Drupal 8 form used by authenticated users which sometimes needs to redirect based on the presence of absence of something in session. I don't want the redirect to be cached.

My form is displayed directly with a route. i.e., the route has a _form default pointing to the form class.

My buildForm method starts like this:

public function buildForm(array $form, FormStateInterface $form_state) 
{
    $form['#cache'] = ['max-age' => 0];

    if (some value not in session) {
        $response = new TrustedRedirectResponse($some_url);
        $response->setMaxAge(0);
        throw new EnforcedResponseException($response);  
    }

    // build the form.
}

I have not been able to avoid the redirect response being cached. It redirects as expected if the session variable does not exist but continues to redirect next time when the session variable does exist.

Users are authenticated so it is the dynamic page cache. drush cr or uninstalling the dynamic page cache "fixes" the problem.

1

I just discovered that it's related to the TrustedRedirectResponse.

A standard Symfony\Component\HttpFoundation\RedirectResponse is not cached.

  • Yes, and you can simply return the response return new RedirectResponse($some_url);, the Form API knows what to do with it. – 4k4 Feb 3 at 19:37
  • Thanks @4k4 I also now see that if I really need a TrustedRedirectResponse for an external url then it's $response->getCacheableMetadata()->setCacheMaxAge(0) to disable caching, not $response->setMaxAge(0) as I was trying. That only sets an http header. – tetranz Feb 3 at 21:04

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.