Skip to main content

How to disable a block programmaticaly with drupal 8

 On my custom theme i have a region with 2 blocks. It is an event region block. The first block is a header block and the second block is a view block that renders the active - running events. However when there are no events the view result is an empty result so nothing is rendered but the header events block remains there. This is the way to hide - unload - disable - remove the extra "orphan" events header block. On your custom_theme.theme file add (if it is not already there) the hook_preprocess_page hook. Now this is a block that only renders on the front page so first i am checking that the current path is the frontpage path (/welcome) and if so i check if my events view returns an empty result array. If it does i remove it from the $variables['page'] array

$current_path = $current_path = \Drupal::service('path.current')->getPath();
if ($current_path === '/welcome'){ 
// /welcome is my frontpage path 
$total_events = views_get_view_result('events','block_1'); 
// view_name : events , view display id: block_1 
if (count($total_events) === 0){ unset($variables['page']['events']); 
//this is the region name 


preprocess theme