1

I have created a module to avoid an objectManager. In this I have

public function getCurrentCategory()
{        
    return $this->_registry->registry('current_category');
}

On my phtml file I call

$myBlock->getCurrentCategory()->getId();

I have full page cache enabled and created a custom submenu on the left sidebar. I want to make the font of the current category bold.

Everything works fine except when I click on an other category the category ID is not refreshed and the visited category remains selected until I manually clean the cache. How can I avoid caching from my function and make sure that each time the getCurrentCategory is refreshed properly?

1
  • this is due to your block is cached. you might have to hole punching – Arif Ahmad Sep 12 '19 at 12:35
1

Try adding this method to your block class

public function getCacheKey()
{
    $storeId = $this->_storeManager->getStore()->getId();
    $catId = $this->getCurrentCategory()->getId();
    return "CATEGORY_SUBMENU_{$catId}_STORE_{$storeId}";
}

That will ensure every category gets an unique cached block instance. The point is that no 2 categories can have the same block in cache that's why we add category id and store id to the cache key.

Additionally you should add this method:

protected function getCacheLifetime()
{
    return 86400;
}

This will set cache lifetime of the block to 1 day (86400 seconds). Adjust as needed.

Not sure if this will fix your issue but it's worth trying :) I've had similar issues before and this has solved them most of the time.

Remember that disabling cache, flushing the cache constantly and cacheable="false" is never the solution.

0

Please try with below way :

public function __construct(
    \Magento\Framework\App\Cache\Manager $cacheManager
) {
    $this->cacheManager = $cacheManager;
}
public function getCurrentCategory()
{        
    $this->cacheManager->flush($this->cacheManager->getAvailableTypes());
   $this->cacheManager->clean($this->cacheManager->getAvailableTypes());

    return $this->_registry->registry('current_category');
}

To put flush and clean cache in your code.

hope its work for you

3
  • Unfortunately it did not help. Thanks for your effort though – TheFrakes Oct 16 '19 at 12:52
  • have another option goto menu layout and add menu block as cachable="false" – Anas Mansuri Oct 16 '19 at 12:54
  • I tried cacheable="false" but still no result. Maybe it does not work out of the design update within the category. – TheFrakes Oct 16 '19 at 13:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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