Hot answers tagged

46

This is full working code with comments. namespace Drupal\module_name\Plugin\Block; use Drupal\Core\Block\BlockBase; use Drupal\Core\Cache\Cache; /** * Provides a Node cached block that display node's ID. * * @Block( * id = "node_cached_block", * admin_label = @Translation("Node Cached") * ) */ class NodeCachedBlock extends BlockBase { public ...


41

I have made following observations after spending a few hours. If there are any gaps or mistakes, do let me know. I will be happy to make editions. First observer that none of the Options under the CACHING are interdependent. If they were you would have seen them under different field sets(or as dependent fields). Make a note of this observation and we will ...


36

For Drupal 7: Drupal has the function drupal_page_is_cacheable() which can be used to set a page to uncacheable. Here is the documentation: https://api.drupal.org/api/drupal/includes!bootstrap.inc/function/drupal_page_is_cacheable/7 For Drupal 8: // Deny any page caching on the current request. \Drupal::service('page_cache_kill_switch')->trigger()...


33

Yes, you can simply clear (TRUNCATE) all cache* tables. This worked well for me: TRUNCATE TABLE cache; TRUNCATE TABLE cache_block; TRUNCATE TABLE cache_bootstrap; TRUNCATE TABLE cache_field; TRUNCATE TABLE cache_filter; TRUNCATE TABLE cache_form; TRUNCATE TABLE cache_image; TRUNCATE TABLE cache_menu; TRUNCATE TABLE cache_page; TRUNCATE TABLE cache_path; ...


29

You can replace the default cache backend to one which does not actually do anything. Simply add this to your settings.php file: if (!class_exists('DrupalFakeCache')) { $conf['cache_backends'][] = 'includes/cache-install.inc'; } // Default to throwing away cache data. $conf['cache_default_class'] = 'DrupalFakeCache'; // Rely on the DB cache for form ...


29

Disable cache for a specific page Disable cache for a custom page from route declaration. If you want to disable cache for a custom controller (Custom module), You have no_cache option (YOUR_MODULE.routing.yml). Example : File : mymodule.routing.yml mymodule.myroute: path: '/mymodule/mypage' defaults: _controller: '\Drupal\mymodule\...


27

You can control the cache in the render array with the #cache element. To disable the cache add: $build['#cache']['max-age'] = 0; In this case the block will not be cached for logged in users or anonymous users with a session. If you want to disable the cache for anonymous users without a session: Disable it either by uninstalling the page_cache ...


26

These are notes from my experiences and might vary from what others experience. I predominantly use LAMP stack and have considered the same in my suggestions. Thumb rules for caching that I generally follow. Process Once Use Multiple Times. Live with stale data when possible Clear Caches infrequently and keep it very specific. When possible do the changes ...


24

You can use drush ev '\Drupal::service("router.builder")->rebuild();' to rebuild the routing information without clearing all the caches.


19

This article has a good rundown of the caching terminology of Drupal: http://www.phase2technology.com/blog/caching-in-drupal/ Summary of the relevant points: Minimum cache lifetime is often misinterpreted as meaning "pages will be regenerated after this much time has passed". What it actually means is that pages will not be regenerated until at least this ...


18

Here is how to use cache tags in the context of custom blocks which I have tried and works but I think it applies to other contexts Use default drupal tags In the build array you can specify cache > tags > node_list and this block content would get invalidated (refreshed) when ANY NODE is changed with nothing else to do on your part public function ...


17

The by far easiest way to do this is to rely on the plugin/block context system. See my answer for How do I make a block that pulls the current node content? You just have to put a node context definition in your block annotation like this: * context = { * "node" = @ContextDefinition("entity:node", label = @Translation("Node")) * } And then use ...


17

A response built from the RedirectReponse class is not cached. So you should not need to set any cache metadata (*). The problem here is probably the page cache for anonymous requests, which caches all responses, even redirects and no matter if they are cachable or not. You can disable this cache by using the kill switch before returning the response: \...


17

Like you said disabling the render cache site wide is not a good idea. If you need this for one content type you can do this in a view alter hook. If you want to disable caching for authenticated and anonymous users you have to set cache max-age = 0 and trigger the kill switch for the internal page cache: function MYMODULE_node_view_alter(array &$build,...


16

The dynamic cache subscribes an event with priority 27. If you want that your code runs before that you have to use a priority >27: public static function getSubscribedEvents() { $events = []; // Run after AuthenticationSubscriber (necessary for the 'user' cache // context; priority 300) and MaintenanceModeSubscriber (Dynamic Page Cache //...


16

Restarting php from within the VM seems to have done the trick. sudo service php5.6-fpm restart


15

For me, the cause was different: some errors are not caught by Drupal's error handler. I used a new DateTime() in my settings.php (probably very rare) It generated an error because the date.timezone setting in my CLI php.ini wasn't set. To find the real error (this is the interesting part of the answer for all of you, I think) : Edit your module.inc, line ...


15

In Drupal 8, you can mention cache as max-age till you want your page ouput to be cached. For removing cache of a particular page(Controller page), write 'max-age' => 0,. public function myPage() { return [ '#markup' => time(), '#cache' => ['max-age' => 0,], //Set cache for 0 seconds. ]; }


15

Yes you can, put this in settings.php or any file loaded by it like settings.local.php: $settings['php_storage']['twig']['directory'] = '/path/to/tmp/folder'; $settings['php_storage']['twig']['secret'] = $settings['hash_salt']; Note that the directoy must exist already.


14

This is all you need to set up caching for a response: $response = CacheableJsonResponse::create($output); return $response; If you use a response that implements the CacheableResponseInterface it will be cached indefinitely. Cache tags When you add a list of taxonomy terms you have to add these tags: $list_tags = $this->entityTypeManager()->...


13

To clear all cache tables run this command in your server terminal. # Truncate cache tables in MySQL regardless of the active cache backend echo "SHOW TABLES LIKE 'cache%'" | $(drush sql-connect) | tail -n +2 | xargs -L1 -I% echo "TRUNCATE TABLE %;" | $(drush sql-connect) -v this will loop through all cache tables and truncate them in one command.


13

The way to do this is to use hook_flush_caches in combination with register_shutdown_function. Example code: /** * Implements hook_flush_caches(). */ function mymodule_flush_caches() { // After caches are cleared we will run mymodule_cache_rebuild() register_shutdown_function('mymodule_cache_rebuild'); // We don't want to add any custom cache-...


13

The easiest way is probably to inspect the HTTP response headers. For example, with your browser DOM inspector tool ( e.g Chrome's "Network" tab ) Cache Miss Here's some sample response headers from drupal.org showing a cache miss. In this case, using Varnish however core Drupal cache also sets similar headers. Cache Hit Here's one showing a standard ...


13

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


13

You can easily create a custom cache tag related to properties on nodes by invalidating it yourself. Based on this article: https://www.drupal.org/project/views_custom_cache_tag I created a custom tag for each node type, that is invalidated on node update: /** * Implements hook_ENTITY_TYPE_presave(). */ function mymodule_node_presave(Node $node) { // ...


13

In Drupal 8.4 you have to set the null cache backend for an additional cache bin, so now there are three: settings.local.php: $settings['cache']['bins']['render'] = 'cache.backend.null'; $settings['cache']['bins']['page'] = 'cache.backend.null'; $settings['cache']['bins']['dynamic_page_cache'] = 'cache.backend.null'; This is because the cached pages for ...


13

But you know the entity ID that you want to have invalidated? Then use \Drupal::entityTypeManager()->getStorage($entity_type_id)->resetCache([$id]);


12

drupal_page_is_cacheable can also be used. Calling: drupal_page_is_cacheable(FALSE); Should do the trick. And for Drupal 8: Drupal::service('page_cache_kill_switch')->trigger();


12

On the admin/config/development/performance page under 'Bandwidth optimization' uncheck "Aggregate and compress CSS files.". If you're looking for more control https://www.drupal.org/project/advagg/ is what you're looking for. Using the development setting in AdvAgg will detect the changes and push them out automatically.


12

There are two different page caches. The Internal Dynamic Page Cache works with all kind of elements like blocks and nodes and is uses the cache tags, cache contexts and cache max-age provided by these elements. The Internal Page Cache is for complete pages for anonymous users and only uses cache tags. You can control the page cache for anonymous users ...


Only top voted, non community-wiki answers of a minimum length are eligible