6

In my module, I can call cache_clear_all() (D7) or drupal_flush_all_caches() (D8), and this would clear the cache for all the nodes.

Is there a way to clear the cache for a single node?

What I need to do is setting up a module that, when it selects a story on a list, it changes the value of a node field. Right now, I change the field value by updating the database table containing that value, but I need to clear the cache for the value to be updated across the site.

Is there's a better way to update a node than directly changing the database table?

0

5 Answers 5

16

If you have the node object, use

use Drupal\Core\Cache\Cache;
...
Cache::invalidateTags($node->getCacheTags());

That's better than to assume the cache tag identifier will be 'node:' . $node->id() forever.

1
  • this did not work for me. Answer below by @vinhdv did work.
    – liquidcms
    Commented Mar 22, 2023 at 18:28
5

The Drupal cache API can be used to clear specific items. Caching back ends can be switched (to memcache, to flat files, etc.) without having to rewrite any code.

Drupal 7

You can try use code :

cache_clear_all('content:' . $node->nid, 'cache_content', TRUE);

Please see document here

Drupal 8

The data that Drupal manages fall in 3 categories:

  1. entities — these have cache tags of the form <entity type ID>:<entity ID>
  2. configuration — these have cache tags of the form config:<configuration name>
  3. custom (for example library_info)

You can try example:

using Cache::invalidateTags

use Drupal\Core\Cache\Cache;

$tags = ['node:' . $node->id()];
Cache::invalidateTags($tags);

You can see Cache tags

0
4

If you have the entity and appropriate entity storage you can use the method resetCache.

$storage = \Drupal::entityTypeManager()->getStorage($entity_type);
$storage->resetCache([$entity_id]);
3

Is there's a better way to update a node than directly changing the database table?

Yes, use the node_load() and node_save() functions as these take care of everything for you including the cache.

Changing the values directly in the database is not advised as any number of modules could have additional handlers added which will not be picked up by altering the database directly.

EDIT: For Drupal 8 use $node = \Drupal\node\Entity\Node::load() instead, then just $node->save()

0
1

For Drupal 8 you can use Clear Specific Cache module

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.