Community Documentation

Tag-sensitive beans

Last updated January 7, 2013. Created by CChow on January 7, 2013.
Log in to edit this page.

If you want blocks to be shown only on pages with specific tags, this is an example implementation.

This will insert beans with the tag-field enabled into a page with similar tags.
It is assumed that both bean type and node type has field_tags.

The bean type is called tag_sensitive_block, and the code simply calls for all beans of this type and collects those that share a tag with the current node. Then it inserts $max_beans beans into the first and second sidebar, switching between them after each insert.

<?php
/**
* Implements hook_page_build().
*/

function my_module_page_build(&$page) {
 
  if (
$node = menu_get_object()) {
  
  
//get taxonomy terms for current node
  
$tids = array();
  
  
$field = $node->field_tags;
  
   if (isset(
$field['und'])) {
   
   
$node_terms = $field['und']; //und is undefined language, replace as necessary
   
   
foreach ($node_terms as $node_term) {
    
$tids[] = $node_term['tid'];
    }
   
   
//get list of relevant tag-sensitive blocks
   
$query = new EntityFieldQuery();
   
   
//get beans with tids that match node tids
   
$result = $query
    
->entityCondition('entity_type', 'bean')
     ->
entityCondition('bundle', 'tag_sensitive_block')
     ->
fieldCondition('field_tags', 'tid', $tids)
     ->
execute();
   
   
//get bean ids
   
if (isset($result['bean'])) {
    
    
$bids = array_keys($result['bean']);
    
    
//populate left and right sidebar with beans
    
$left_sidebar = true; //alternate between first and second sidebar
    
$max_beans = 6; //maximum 3 beans in first sidebar, 3 beans in second sidebar
    
$bean_counter = 0;
    
     foreach(
$bids as $bid) {
     
     
//stop at max beans
     
if ($bean_counter > $max_beans) {
       break;
      }
     
     
//load bean
     
$bean_array = entity_load('bean', array($bid));
     
$bean = $bean_array[$bid];
     
$bean_delta = 'delta';
     
$delta = $bean->$bean_delta;
     
     
//determine placement
     
if ($left_sidebar) {
      
      
$page['sidebar_first'][$delta]['content']['#markup'] = drupal_render(bean_view($bean));
      
$left_sidebar = false;
      
      } else {
      
      
$page['sidebar_second'][$delta]['content']['#markup'] = drupal_render(bean_view($bean));
      
$left_sidebar = true;
      
      }
     
     
$bean_counter += 1;
     }
    }
   }
  }
}
?>

About this page

Drupal version
Drupal 7.x
Audience
Programmers
Level
Intermediate
Keywords
bean, block, tag

Site Building Guide

Drupal’s online documentation is © 2000-2013 by the individual contributors and can be used in accordance with the Creative Commons License, Attribution-ShareAlike 2.0. PHP code is distributed under the GNU General Public License. Comments on documentation pages are used to improve content and then deleted.
nobody click here