5

I have a form that is pre-populated with information specific to an anonymous user's session information. However, the form appears to get cached for all anonymous users by default.
'Internal Dynamic Page Cache' is enabled, 'Internal Page Cache' is not.

How do I disable caching of this form? It should be rebuilt fresh every time it is displayed.

  • is it a custom form ?? – Shreya Shetty Sep 14 '16 at 6:03
  • 1
    In your hook_form_alter() do this if($form_id == "my_form") { \Drupal::service('page_cache_kill_switch')->trigger();} – batMask Sep 10 '18 at 10:02
10

To update:

In order to prevent a form from caching at all, you can include the following #cache key in your form:

$form['#cache'] = ['max-age' => 0];
3

In your mymodule.module file, located at the root of your module directory:

/**
 * Workaround to prevent form caching for anonymous users.
 */
function mymodule_form_myregistration_form_alter() {
    \Drupal::service('page_cache_kill_switch')->trigger();
}

/**
 * Workaround to prevent form caching for anonymous users.
 */
function mymodule_form_mylogin_form_alter() {
    \Drupal::service('page_cache_kill_switch')->trigger();
}

This is using Drupal 8's Form Alter

  • I have a similar problem (using search api) for anonymous users, and this solved it simply. Thank you! – hkong Mar 7 at 21:12
2

The correct way to do this is with:

$form['#cache']['contexts'][] = 'session';

At some stage between Drupal versions max-age has stopped working

  • Yay! This works! I originally commented that it wasn't working, but turned out I did something silly; it does work, so thank you very much. – Spudley Jul 11 at 13:21

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.