Skip to content

Instantly share code, notes, and snippets.

@jessehs
Last active August 29, 2015 14:05
Show Gist options
  • Save jessehs/13383de285e0f416000f to your computer and use it in GitHub Desktop.
Save jessehs/13383de285e0f416000f to your computer and use it in GitHub Desktop.
Add arbitrary classes to a Bean block.
<?php
/**
* Implements hook_preprocess_block().
*
* Adds a few helpful theming classes to a bean block:
* The bean's view mode, bundle (bean type), and the value of an arbitrary
* field, 'field_image_size'. Use this for beans placed using core blocks or
* the Context module.
*/
function THEME_preprocess_block(&$variables) {
$block = $variables['block'];
$block_module = $block->module;
$elements = $variables['elements'];
if (!empty($block_module) && ($block_module == 'bean')) {
// The location of the Bean array within $variables is a moving target
// E.g. use of the Context Module will change it's location to within
// $elements['content']. Try the likely locations.
if (array_key_exists('bean', $elements)) {
$bean_array = $elements['bean'];
}
else if (isset($elements['content']) && array_key_exists('bean', $elements['content'])) {
$bean_array = $elements['content']['bean'];
}
else {
$bean_array = FALSE;
}
// Test that the Bean array has been found.
if ($bean_array) {
$mystery_key_array = element_children($bean_array);
if ($mystery_key_array) {
$bean = $bean_array[$mystery_key_array[0]];
// Add bean type and view mode as classes to the block.
if (isset($bean['#entity']->data['view_mode'])) {
$variables['attributes_array']['class'][] = str_replace('_', '-', $bean['#entity']->data['view_mode']);
$variables['attributes_array']['class'][] = str_replace('_', '-', $bean['#bundle']);
}
// Add an image-size class.
if (isset($bean['#entity']->field_image_size[LANGUAGE_NONE][0]['value'])) {
$variables['attributes_array']['class'][] = str_replace('_', '-', $bean['#entity']->field_image_size[LANGUAGE_NONE][0]['value']);
}
}
}
}
}
/**
* Preprocess logic for Panels panes.
*
* Adds a bean's bundle name as a class.
*/
function rTHEME_preprocess_panels_pane(&$vars) {
if (array_key_exists('bean', $vars['content'])) {
$bean_array = $vars['content']['bean'];
if ($bean_array) {
$mystery_key_array = element_children($bean_array);
if ($mystery_key_array) {
$bean = $bean_array[$mystery_key_array[0]];
// Add bean type and view mode as classes to the block.
if (isset($bean['#entity']->data['view_mode'])) {
$vars['attributes_array']['class'][] = str_replace('_', '-', $bean['#entity']->data['view_mode']);
$vars['attributes_array']['class'][] = str_replace('_', '-', $bean['#bundle']);
}
}
}
}
}
@aprohl5
Copy link

aprohl5 commented Aug 14, 2014

@jessehs does the 'variables'variable on line 12 need to be changed to anything?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment