0

I tried setting the cache max-age to 0 in hook_views_pre_view, in hook_views_pre_build and in hook_views_query_alter but it just doesn't work.

Eg:

function my_module_views_pre_build(ViewExecutable $view) {
  $view->element['#cache']['max-age'] = 0;
}

The views caches the response until the caches are cleared.

I need to do this programatically because I need to force the views to not cache the results for more than 10 minutes based on some conditions.

Later Edit: The issue discussed in "How to use max-age" does not apply in my case. I know how to use cache tags, contexts and max-age for pages/rendered arrays and they work just fine. But for views I can't make them work.

  • Does this answer your question? How to use max-age – Hudri Mar 12 at 10:33
  • No, it doesn't help. I know how to use cache tags, contexts and max-age for pages/rendered arrays and they work just fine. But for views I can't make them work. – Marius Ilie Mar 12 at 11:24
0

Views has a cache plugin for no caching which you can configure in UI. Better use this method, setting a cache max-age in a hook might not be enough to disable all caching in a view. Also you can't control traffic from anonymous users by this. If you have dynamic views you want to deliver to anonymous users uninstall the Internal Page Cache and set the Cache-Control headers in /admin/config/development/performance accordingly.

  • I don't care about anonymous users, they don't have access to these views. I don't want to disable caching. I need to keep current views caching (by tags) and also add a max-age (10 minutes) for some of them based on some conditions. – Marius Ilie Mar 12 at 11:24
0

Does it need to be done programmatically? Why not do it within the views UI, you can set the caching to "Time-based" and set a 5min limit.

This is in the "Advanced" section and the 3rd from bottom item

  • because I also need to have cache cleared when a cache tag is invalidated, not just when the max-age is reached and because the max-age cache should be set based on some conditions. – Marius Ilie Mar 12 at 11:47
  • Have you tried this though? As I believe having a time based doesn't purely mean that's it cached for that time. If a cachetag on the view gets invalided the view will still have its caches cleared – Leigh Mar 12 at 11:52
0

I had to use the cache_control_override module recently because the caching was not working for anonymous users when set from the views_ui or even programmatically. This module just needs to be enabled and has no configuration and my views caching started working.

Sounds you might have the same problem. You can give this module a try.

The module solves this problem with bubbling the cachability data up to the page response level. Find out more info on the project's page.

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.