Problem/Motivation
The cache invalidation on the Status value is not updating despite many efforts. It has been discussed in
π
Add Field cache for 'Currently Open/Closed' Status formatter
Fixed
,
π
Fix Field cache for anonymous users using Cron job in Status formatter
Closed: won't fix
,
π
Cron for cache handling breaks badly
Fixed
at least.
Steps to reproduce
* have all Drupal caching on
* set the closing time to be something that happens soon and let the time pass
* reload page. The status flag should change to "closed" but it doesn't. Neither for authenticated nor unauthenticated requests.
Proposed resolution
The solution proposed in
β¨
Fix Field cache for anonymous users using JS callback in Status formatter
Fixed
is a often used resolution for this and other use cases.
However, it needs many infrastructure in order to be working.
Another solution would be to use the '#lazy_builder' render instruction.
Since the problem only seems to be existing for anonymous users, the solution proposed here, is to DISABLE the caching for entity display with a Status formatter, only for anonymous users.
This is the least intrusive way. If this solution is not sufficient in the real world, we can revisit the other above mentioned solutions
/**
* @see https://drupal.stackexchange.com/questions/228483/disable-form-or-block-cache-for-anonymous-users
* Cache tags are used to invalidate cache. Like if a cache element is tagged with node:1 and node with nid 1 is updated, then all cache containing node:1 cache tag is invalidated (other tags are also invalidated).
* Cache contexts are used if cached element exists in multiple variations based on something like the query arg. What happens is that multiple cache entries are created and they will all be invalidated based on the same logic (cache tags).
*/
So, either via
public function getCacheContexts() {
// Do not set caching for anonymous users by adding session a context.
if (\Drupal::currentUser()->isAnonymous()) {
return [
'session',
];
}
return [];
}
but this will create a cache entry for each page visit, we will use:
public function getCacheMaxAge() {
// Do not set caching for anonymous users.
if (\Drupal::currentUser()->isAnonymous()) {
return 0;
}
...
}