Drupal 7: Alter one region based on properties of another region

Published by Lennart Van Vaerenbergh on February 5, 2016

This blog post is about Drupal 7 regions, the main blocks of a Drupal website in which content appears. There is a hook out there, template_preprocess_region(), which let's you alter the variables used for rendering the region. One setback is that each region can be altered on its own using this hook, unable to use information from other regions. This is a possible solution.

Say you want to add css classes to region_x only when region_y is also visible (= has content) on your Drupal page. This is how you can do it.

template.php
<?php
/**
 * Implements hook_page_alter().
 */
function MYTHEME_page_alter(&$page) {
  if (isset($page['region_y']) && element_get_visible_children($page['region_y'])) {
    $page['region_x']['#region_y_visible'] = TRUE;
  }
  else {
    $page['region_x']['#region_y_visible'] = FALSE;
  }
}

/**
 * Implements template_preprocess_region().
 */
function MYTHEME_preprocess_region(&$vars, $hook) {
  if ($vars['region'] == 'region_x') {
    if (isset($vars['elements']['#region_y_visible']) && $vars['elements']['#region_y_visible']) {
      // Region_y is visible, so we can alter for example classes of region_x.
      $vars['classes_array'][] = 'new-class';
    }
  }
}
Where 'region_x' and 'region_y' are the machine names of the regions. Also make sure the array key keeping the value you want check later on starts with a '#'. If not, drupal will consider it a child element of the render array, which will cause warnings due to being invalid.

Good luck!

Add new comment

(If you're a human, don't change the following field)
Your first name.
(If you're a human, don't change the following field)
Your first name.
CAPTCHA
This challenge is for testing whether or not you are a human visitor and to prevent automated spam submissions.