I use Drupal 8 and I want to disable caching for a specific content type in full view mode.
I've found how to disable caching for all view modes, but I want to disable it for only a specific content type.
How can I do that?
Drupal Answers is a question and answer site for Drupal developers and administrators. It only takes a minute to sign up.
Sign up to join this communityI use Drupal 8 and I want to disable caching for a specific content type in full view mode.
I've found how to disable caching for all view modes, but I want to disable it for only a specific content type.
How can I do that?
You need to set max-age 0 in e.g. hook_node_view().
function yourmodule_node_view(array &$build, NodeInterface $node, $display, $view_mode) {
if ($node->getType() == 'yourtype' && $view_mode == 'full') {
$build['#cache']['max-age'] = 0;
}
}
That said, I recommend you find a way to make caching work. There are concepts like lazy_builder that allow you cache most of a node and only dynamically build a small part in it.
Also note that this does not disable the page cache for anonymous users. If you need that too, which I would recommend even more to try and avoid, then you also need:
\Drupal::service('page_cache_kill_switch')->trigger();
Update, answer is getting too long to post in a comment:
Ah, flag. How do you hide the flag for the author? Are you using the latest D8 and flag version?
If you look at flag_entity_view(), you can see that flag is already doing exactly that. It registers a so called lazy builder and enables a thing called placeholdering. It does that to show a flag/unflag link depending on the user. You probably just set #access on that element right now.
Flag is supposed to have access hooks but I think they don't work right now. See https://www.drupal.org/node/2584299. Follow that issue, once that is resolved, you can just implement that.
But for now, you can just switch out the lazy builder callback there with your own for now that does your additional check and then does what the existing one does. And it will just work.
You can also use the option
no_cache: TRUE
in your route declaration as described here: https://www.drupal.org/node/2463533