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();
	}
}

Comments

Submitted by codimth on Mon, 10/12/2020 - 10:13 Permalink

@David  you can use \Drupal::service('page_cache_kill_switch')->trigger(); 

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();
	}
}
Add new comment

Restricted HTML

Search

Page Facebook

Become a patron

If you need some help or you search a Drupal freelancer don't hesitate to contact us.

 

Contact Us

All the content is FREE but I still need your help

 

Become a patreon