How to Pass Variables Horizontally and Vertically in Drupal

There are some variables($node, $page,etc) you depend more than on anothers in Drupal. Its important to have access them when you need. In the following, we describe two ways -“top to down” and “left to right” to pass and accesses any variable at any part of the execution in Drupal

Top to Down …or Vertical

A good example, would be passing some variable from page scope to the node scope

function THEME_preprocess_page(&$vars, $hook){
   $vars['node']->bazar_product = $prod_default;

Since page scope calls theme function ‘node’ to render the node, it takes the variable – vars as parameter(see theme function for node). You can utilize that by storing your custom variables into $vars making it accessible in the node scope – hook_preprocess_node().
For passing between any other scope, first find what theme function is called for rendering the children and look at this theme’s function declaration to see exact variables being passed down to children

Left To Right …or Horizontal

Often times we need to know what node type is set for the current request in the html scope – hook_preprocess_html(), however the node type is processed and set during page scope. Since there are no variables passed between hook_preporcess_page and hook_preporcess_html, the variables such as node type is not shared between, however. We need the node type in the html scope, so we can render particular template. To pass variables from one scope to another horizontally, we utilize cache as following:

//get the current content from cache
$content = drupal_set_page_content();
//indicate that you are not adding content but just reading it by setting static variable 'system...added' to False 
$system_main_content_added = &drupal_static('system_main_content_added');
$system_main_content_added = FALSE;

The variable content will have variables from hook_preproccess_page scope. Its important to note, that cache may not always work because you may be asking too early.

Leave a Reply

Your email address will not be published. Required fields are marked *