When you have a larger project you probably have both internal page cache as internal dynamic page cache module enabled. In my case I do. But I have a section on my website containing custom entities ('Contest') where I would like to have custom-tailored control of caching of the detail page (contest/1). This is what I found so far:
/**
* Implements hook_entity_view_alter()
* Disable caching on all contest entity types
*/
function mymodule_entity_view_alter(array &$build, Drupal\Core\Entity\EntityInterface $entity, \Drupal\Core\Entity\Display\EntityViewDisplayInterface $display) {
$types = ['contest'];
if (in_array($entity->bundle(), $types)) {
$build['#cache']['max-age'] = 0;
\Drupal::service('page_cache_kill_switch')->trigger();
}
}
Is this the only way? I'd expect to have a more clean way, in my Contest.php perhaps? Looking forward to possible answers!
getEntityTypeId()
. If this is the case you could add the optionno_cache: TRUE
to the entity routes (route_provider in your entity class Contest).