0

I have a little issue regarding my custom block module. The module itself fetches weather data via json-request and the data is shown as a 4-day weather forecast to the user. As the weather should be actualized every day I want to set a "maximum cache time" or even disable caching for the whole block. Right now I would have to flush the cash manually every day.

After a little bit of research to that topic I found out that using 'max-age' in the build() function would do the trick but it does not affect the caching for anonymous users at all.

Using \Drupal::service('page_cache_kill_switch')->trigger(); would disable the cache for a specific page or content-type but I don't want to disable the caching for a whole page at once.

So how can I trigger the caching for my custom-block? Or is there even a way to disable the caching for a certain part of the code e.g. the json-request in my case?

  • 1
    You can use lazy builder or fetch data in js. – user21641 Sep 2 '17 at 15:00
1

This is a known issue Bubbling of elements' max-age to the page's headers and the page cache.

The Internal Page Cache is designed for database content, which is handled by cache tags. So a workaround would be to add a custom cache tag to the block

$build['#cache']['tags'][] = 'weather_forecast';

which will bubble up to the page level and so you can invalidate both cached items, block and page, in a cron job:

/**
 * Implements hook_cron().
 */
function mymodule_cron() {
  \Drupal\Core\Cache\Cache::invalidateTags(['weather_forecast']);
}

All credit goes to @Berdir: Cache max-age and varnish ESI

  • Thank you. That did the job for me! In my case i had to declare the custom cache tag with '#cache' => [ 'tags' => ['weather_forecast'], ], to get it to work. – tinytree Sep 2 '17 at 21:26

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.