14

After login. I'm adding one sidebar block. Once I clear cache then only updates variable or it's value.

namespace Drupal\test_demo\Plugin\Block;

use Drupal\Core\Block\BlockBase;

/**
 * Provides 'Sidebar' Block
 *
 * @Block(
 *   id = "sidebar_block",
 *   admin_label = @Translation("Sidebar Block"),
 *   category = @Translation("Sidebar Block"),
 * )
 */

class SidebarBlock extends BlockBase {
  public function build() {
    return [
      '#markup' => $this->t('Sidebar'),
      '#cache' => [
            'max-age' => 0,
          ]
      ];
  }
}

In mytheme.theme

function theme_preprocess_block(array &$variables) {
  echo $variables['elements']['#id'];
}

How can I stop that block to being cached. So once I refresh the page. It loads the value immediately.

4
  • 1
    Your build method code looks fine. Did you clear the cache? I see your block does not have an ID on the code you posted above. Did you leave that part out? or did you not declare an ID for your block?
    – No Sssweat
    Commented Dec 13, 2017 at 4:48
  • 1
    Hi @NoSssweat update code. Yes checked still issue
    – Mike
    Commented Dec 13, 2017 at 5:10
  • 1
    Try switching to the default Drupal theme Bartik and see if the issue persists there. Also, since you're using PHP 7 syntax, I assume your server is running on PHP 7, right?
    – No Sssweat
    Commented Dec 13, 2017 at 5:15
  • 1
    Using PHP 7 correct
    – Mike
    Commented Dec 13, 2017 at 5:19

2 Answers 2

34

Got the solution via https://stefvanlooveren.me/blog/disable-block-caching-drupal-8

Add below function to your block

https://stefvanlooveren.me/blog/disable-block-caching-drupal-8

public function getCacheMaxAge() {
    return 0;
}

https://www.drupal.org/docs/8/api/cache-api/cache-max-age

6
  • 1
    Nice find, altho I am convinced your original method should've worked, don't have time to test right now.
    – No Sssweat
    Commented Dec 13, 2017 at 6:12
  • 1
    Yes @NoSssweat Yes it works fine now :)
    – Mike
    Commented Dec 13, 2017 at 7:25
  • @NoSssweat This is the solution that works for me too, I don't know if the '#cache' was removed from the render arrays. Commented Dec 13, 2017 at 16:06
  • This still work, and is so far the purest method
    – Tarto
    Commented Dec 2, 2019 at 13:19
  • Is this working on drupal9 too?
    – Matoeil
    Commented Jul 19, 2021 at 8:49
-1

You can simply switch Caching to None on advanced options of view's block

1
  • 6
    Nobody ever mentioned Views.
    – Gábor
    Commented Nov 14, 2020 at 10:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.