Activate Context To Rebuild Page More Than Once Per Page Load in Drupal

There was a situation where we needed to rebuild a page content and do it from Page scope(hook_preprocess_page). Most of the time the page content is altered via hook_page_alter(), however. This adds overhead of setting up a separate function, filtering request and other things all of which creates another dependency to the logic already handled from the hook_preprocess_page(). In this post, we cover how to accomplish the same thing from Page scope(hook_preprocess_page) to force rebuild content after making changes to it.

Here, we use Context module to manage blocks.

1. Activate Context

The context is what sets which blocks to display and in which region. Depending on the request, we activate a different context as following:

function MODULE-NAME_preprocess_page(&$vars){
      if(module_exists('context')){
            $context = context_load('shop');
            (isset($context->name)) ? context_set('context', $context->name, $context) : watchdog(WATCHDOG_NOTICE, 'Context with name - shop does not exist');
     }
}

Here, the context – shop is loaded and then set to be active.

The changes are made, however, the blocks and regions are already built and set in the $vars[page] variable ready to be rendered in the template file.

2. Rebuild the Blocks and Regions

Although we activated certain context, the blocks of this context will not show up unless we rebuild the blocks and regions for the content:

function MODULE-NAME_preprocess_page(&$vars){
...
//rebuild blocks and regions
//            block_page_build($vars['page']);
            context_page_build($vars['page']);

            //set the new changes in cache
            drupal_set_page_content($vars['page']);
...
}

Here, first we rebuild blocks managed by context in the line 5. In the line 4, we are including uncommitted line if the changes would have been made for blocks managed by Block module. Afterwards, the cache for the content is reset with our new changes.
Thats all, now the content is displayed with the new changes

Leave a Reply

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