Score:2

Node ID caching on hook_form_alter()

in flag

I have a webform with an email field. I am embedding the webform on each node, with a field on the node for the email address.

I implemented hook_form_alter() in my .theme file that loads the node using $node = \Drupal::routeMatch()->getParameter('node');.

I can then load the node and get the proper email address and set it in the webform. The problem is that the node is cached for anonymous users. It doesn't matter what node I'm on, $node->id() always returns the same, cached node ID.

I have tried either these lines, but the node ID is still the same.

\Drupal::service('page_cache_kill_switch')->trigger();
$vars['#cache']['max-age'] = 0;

I understand I have to clear cache tags and cache context, but none of the examples shows exactly how to do this in hook_form_alter().

How can I properly clear the cache?

Score:5
cn flag

When you get route parameters you need this cache context:

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

You might also want to add the node cache data so that the form gets invalidated when the node is saved with a different field value:

$renderer = \Drupal::service('renderer');
$renderer->addCacheableDependency($form, $node);

The cache context is applied to the form and all page elements where the form is placed in. So this works no matter where you embed the form.

If the form is embedded within a node, getting the node from the route match is probably not the best idea. You should use the node or node ID as parameter when calling the form. Then you can try the answer from @sonfd because you don't need separate cache keys for the node and webform.

in flag
This is what did it. Thank you so much!! $form['#cache']['contexts'][] = 'route';
Score:3
in flag

The problem is that the webform gets cached with the $node data from the first node visited, but you need the webform to be unique per node.

You can unset the cache keys for your webform - this will prevent the webform from being cached on its own, but will still allow the webform to be cached with its parent (the node), with all of the webform's cache metadata bubbling up.

In your hook_form_FORM_ID_alter() (the one you're using to set the email address), you can unset the cache keys like:

if (isset($form['#cache']['keys']) {
  unset($form['#cache']['keys']);
}
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.