Contextual blocks

Posted on 29 Mar
Sometimes you want to display content from a node in a separate region, like a sidebar. A nice way of doing that is to add an additional field to your content type. Call it something like, "sidebar body". Hide it's display under "manage display". Then create a new view block that uses a 'contextual filter' of type 'Content: Nid'. Check off "provide a default value" and select "Content ID from URL" in the dropdown. Add your 'sidebar body' field into the view fields then put your block in the sidebar. The contents of that field will now display in the block on the page where the rest of the node content is displayed.
What about the title
Instead of hard setting the title for that block, make it dynamic. Add an additional field to your content type called, "sidebar body title". Set the title for that block to your new field through hook_block_view_alter(). Here's an example from a project I did recently,
/** * Implementation of hook_block_view_alter() */ function awesometheme_block_view_alter(&$data, $block) { //We grab the field 'sidebarbody title' (in 'basic_page' content type) from the node and set it equal to the title //of the block that spits out 'sidebar body' if (isset($block->info)) { if ( $block->info == 'View: Basic Node Content Revisions: Sidebar' ) { if ($node = menu_get_object()) { if (isset($node->field_sidebar_title[$node->language]['0']['value'])) { $block->title = $node->field_sidebar_title[$node->language]['0']['value']; } } } } }
Using the devel module (include kpr($data) to look inside data, kpr($block) to look inside block) I looked for my block and something unique about it. In this case I grabbed the contents in block->info because it was unique about the block. menu_get_object() is another way of looking at the node instead of using node_load(), the node is often stored in the menu_router on node pages. Looking at the contents of the node (using kpr($node) inside the menu_get_object() statement), I set the sidebar_title field equal to the title of the block.
*update: This can be also done through Display Suite region to block functionality, described in the seventh screencast - link on the module page.


