How to disable a block programmaticaly with drupal 8

Aug
2020
11
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.
<?php
function mytheme_preprocess_page(&$variables) {
//We will add code here
}
?>
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.
<?php
function mytheme_preprocess_page(&$variables) {
 
$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
   
}

  }
}

?>
this is an arrow pointing back to the top of the page