2

I have a form submit function that is meant to invalidate the cache of every node if a specific field is altered. Here's how I'm attempting it.

$config = $this->configFactory
  ->getEditable('my_config.settings')
  ->get();
if ($form_state->getValue('global')['header_button'] != $config['global']['header_button']){
  // Header Button Changed
  \Drupal\Core\Cache\Cache::invalidateTags(['node_list']);
} 

From what I've researched I assumed \Drupal\Core\Cache\Cache::invalidateTags(['node_list']); would invalidate the cache on every node, but the changes to the nodes are not appearing to anonymous users. Not sure if it matters but the change that is made affects what is rendered in region--header.html.twig rather than node.html.twig.

I've looked at How do I invalidate the cache of an entity? but the answers there did not work.

7
  • 3
    What is your use case? You are almost definitely trying to apply a sledgehammer approach to a situation that needs finesse, but you haven't explained your use case for us to be able to advise you accordingly. That said, you should be able to do it with \Drupal\Core\Cache\Cache::invalidateTags(['node']);, but it's a sledgehammer solution and the performance on your site will take a hit, particularly if you have a lot of nodes.
    – Jaypan
    Commented Jan 25, 2023 at 22:37
  • I am trying to decide if it is really necessary to explicitly invalidate tags in this case. Does the changing content have caching metadata?
    – mona lisa
    Commented Jan 25, 2023 at 22:38
  • 3
    I would probably add the cache tag for this config key to the field in question, negating the need to invalidate anything as the system would handle it.
    – Jaypan
    Commented Jan 26, 2023 at 0:01
  • @Jaypan The reason why every node needs to be invalidated is because I've built a custom config that allows the admin to globally add a button that appears on every page. Because this appears on every page each node would need to be invalidated.
    – Amy
    Commented Jan 26, 2023 at 1:29
  • See my above comment
    – Jaypan
    Commented Jan 26, 2023 at 2:55

1 Answer 1

1

The node_list cache tag is indeed invalidated by every node change but it's not the other way, that it invalidates every node. The cache tag is only added to the result of node entity queries, not to single nodes.

For a configuration change, it's OK to invalidate the entire render cache, at least for a typical configuration option not changed in the normal operation of the website. For example, Drupal core does the same when theme settings are saved. This is not as time-consuming as clearing the entire Drupal cache:

Cache::invalidateTags(['rendered']);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.