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

Latest Articles

Using drupal/core-composer-scaffold to prevent rewriting .htaccess or robots.txt file admin_pixelthi… Sun, 12/01/2024 - 16:49 Using drupal/core-composer-scaffold to prevent rewriting .htaccess or robots.txt file

Using drupal/core-composer-scaffold to prevent rewriting .htaccess or robots.txt file

composer
Controlling ckeditor styling options with hook_editor_js_settings_alter admin_pixelthi… Thu, 05/16/2024 - 10:49 Controlling ckeditor styling options with hook_editor_js_settings_alter

Controlling ckeditor styling options with hook_editor_js_settings_alter

php hook hook_editor_js_settings_alter hook_field_widget_single_[WIDGET_TYPE]_form_alter
Upgrading Drupal 9 Modules for Drupal 10: A Simple Guide admin_pixelthi… Tue, 09/05/2023 - 14:18 Upgrading Drupal 9 Modules for Drupal 10: A Simple Guide

Upgrading Drupal 9 Modules for Drupal 10: A Simple Guide

composer drupal9 drupal10