Drupal - How do I prevent a form from being cached for anonymous users?

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];

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


The correct way to do this is with:

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

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

Tags:

Forms

Caching

8