Disable cache 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.

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

}

}

No comments:

Write a program in PHP to reverse a number

A number can be written in reverse order. For example 12345 = 54321 <?php   $ num = 23456;   $ revnum = 0;   while ($ num > 1)   {   $...