n Disable cache for a block in Drupal 8 | CodimTh

Please Disable Your Browser Adblock Extension for our site and Refresh This Page!

our ads are user friendly, we do not serve popup ads. We serve responsible ads!

Refresh Page
Skip to main content
On . By CodimTh
Category:

Code snippet that can be used to disable caching for a block in Drupal 8.

use $vars['#cache']['max-age'] = 0 to stop  block being cache in drupal 8.

/**
 * Implements hook_preprocess_HOOK()
 */
function mytheme_preprocess_block(&$vars) {
  if($vars['derivative_plugin_id'] == 'block-id-name') {
    $vars['#cache']['max-age'] = 0;
  }
}

for custom Block you can use getCacheMaxAge() method like this:

class MyModuleBlock extends BlockBase {
  /**
   * {@inheritdoc}
   */
  public function build() {
  }

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

 

Also you can use \Drupal::service('page_cache_kill_switch')->trigger(); to disable the cache for anonymous users and all others too.

Example:

function fest_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
     if ($form_id == "node_something_form") {
           	//disable the form cache for anonymous users and all others too
	\Drupal::service('page_cache_kill_switch')->trigger();
	}
}

Riadh Rahmi

Senior Web Developer PHP/Drupal & Laravel

I am a senior web developer, I have experience in planning and developing large scale dynamic web solutions especially in Drupal & Laravel.

Web Posts

Search

Page Facebook