Reputation: 3854
When a return a render array for a block and specify the following:
'#cache' => [ 'max-age' => 0 ]
Drupal STILL caches the block!
How do I properly disable it?
Upvotes: 1
Views: 4145
Reputation: 3192
Override the getCacheMaxAge
of your block's class with the value 0
.
class MyBlock extends BlockBase {
/**
* {@inheritdoc}
*/
public function build() {
// Returns the block content as a render array
}
/**
* {@inheritdoc}
*/
public function getCacheMaxAge() {
return 0;
}
}
Upvotes: 4
Reputation: 3854
As implied here in the Drupal 8 documentation, you must invalidate the tags associated with the block.
How I ended up "disabling" caching for a specific block was to use an event subscriber to invalidate the tags for said block.
Event Subscriber:
class MyBlockCacheInvalidator implements EventSubscriberInterface {
protected $cacheTagsInvalidator;
public function __construct(CacheTagsInvalidatorInterface $cache_tags_invalidator) {
$this->cacheTagsInvalidator = $cache_tags_invalidator;
}
public function onRequest(KernelEvent $event) {
$this->cacheTagsInvalidator->invalidateTags(['my_block_tag']);
}
public static function getSubscribedEvents() {
$events = [];
$events[KernelEvents::REQUEST][] = array('onRequest');
return $events;
}
}
Service Entry:
services:
my_block.cache_invalidator:
class: Drupal\my_module\EventSubscriber\MyBlockCacheInvalidator
arguments: ['@cache_tags.invalidator']
tags:
- { name: event_subscriber }
Block Build Response:
return [
'#theme' => 'my_block_theme',
'#var1' => $some_value,
'#cache' => [
'max-age' => 0,
'tags' => ['my_block_tag']
],
];
This solution worked for me, but it isn't efficient.
Upvotes: 2