1

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?

3

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

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

You can see Cache tags

2

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

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()

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.