logo

Using custom code disable cache from menu block in drupal 8

14
March

Using custom code disable cache from menu block in drupal 8
By: Anonymous | Published On: Tue, 03/14/2023 - 14:47

To disable caching for a specific menu block in Drupal 8 using custom code, you can implement the hook_block_view_alter hook in your custom module or theme. Here's an example implementation:

/**
 * Implements hook_block_view_alter().
 */
function mymodule_block_view_alter(array &$build, \Drupal\Core\Block\BlockPluginInterface $block) {
  if ($block->getPluginId() === 'system_menu_block:my-menu') {
    // Disable caching for the menu block.
    $build['#cache']['max-age'] = 0;
  }
}

Replace mymodule with the machine name of your custom module, and my-menu with the ID of the menu block you want to disable caching for.

This code checks if the current block is the one you want to target (system_menu_block:my-menu) and sets the cache max-age to 0, effectively disabling caching for this specific block.

Need Help ?