Disable cache for block in Drupal 8+

0
2
Disable cache for block in Drupal 8+
Disable cache for block in Drupal 8+

In this post, I will share a tip to disable cache for block in Drupal 8+.

To disable cache for block in Drupal 8+, we will make use of preprocess_HOOK() to implement for block.

function MODULE_preprocess_block(&$variables) {
    if($variables['derivative_plugin_id'] == 'block-id') {
        // by setting `max-age` to 0, block cache will be disabled
        $vars['#cache']['max-age'] = 0;
    }
}

For custom block, we can extends Drupal\Core\Block\BlockBase class and create a function getCacheMaxAge() to return 0.

class CustomBlock extends BlockBase {
  /**
   * @return int
   */
  public function getCacheMaxAge() {
    return 0;
  }
}

However, for Drupal 8.4 and above, if cache remains still, you might need to enforce the block the cache regardless of whatever cache settings are.

\Drupal::service('page_cache_kill_switch')->trigger();

It is something you should put into the BlockBase::build() method:

class MyModuleBlock extends BlockBase {
    /**
     * {@inheritdoc}
     */
    public function build() {
        //...some code before

        // enforce cache disable for the block
        \Drupal::service('page_cache_kill_switch')->trigger();

        //... some code after
    }

    /**
     * @return int
     */
    public function getCacheMaxAge() {
        return 0;
    }
}

That’s how you disable cache for block in Drupal 8.

Have fun!