You are here

function viewblock_topclass_preprocess_block in View block top class 7

Adds classes to the top level block element that are defined in a view blocks 'CSS Class' field This function depends on the views option 'Hide contextual links' being set to 'no', since this is the only location that views stores information about the view in the block.

File

./viewblock_topclass.module, line 8

Code

function viewblock_topclass_preprocess_block(&$variables) {
  if ($variables['block']->module == 'views') {

    // First, try to get info about the view from contextual links - The contextual links module does not have to be on,
    // but 'Hide contextual links' must be set to 'no' (the default).  We try this method first because its usually
    // available and may save us some performance overhead if the view object is already present.
    if (isset($variables['elements']['#views_contextual_links_info']['views_ui']['view'])) {
      $view = $variables['elements']['#views_contextual_links_info']['views_ui']['view'];
      $display_id = $variables['elements']['#views_contextual_links_info']['views_ui']['view_display_id'];
    }
    else {

      // If the delta doesn't contain valid data return nothing.
      $explode = explode('-', $variables['block']->delta);
      if (count($explode) != 2) {
        return;
      }
      list($name, $display_id) = $explode;
      $view = views_get_view($name);
    }

    // If we got a view and a display name, we can get the classes from it and put them on our block
    if (!empty($view) && !empty($display_id)) {

      // Get the css string as defined by the user for this display
      if (isset($view->display[$display_id]->display_options['css_class'])) {

        // If the css class is set but is empty, return - the user doesn't want to use a class
        if (!empty($view->display[$display_id]->display_options['css_class'])) {
          $view_css_string = $view->display[$display_id]->display_options['css_class'];
        }
        else {
          return;
        }
      }
      elseif (isset($view->display['default']) && !empty($view->display['default']->display_options['css_class'])) {
        $view_css_string = $view->display['default']->display_options['css_class'];
      }
      else {

        // There's no CSS class, we can't do anything
        return;
      }

      // There may be more than one class separated by a space, parse them out:
      $view_classes = explode(' ', $view_css_string);
      if (!empty($view_classes)) {

        // Add each class to the blocks top level container with the string '-container' concatenated
        foreach ($view_classes as $view_class) {

          // Strip whitespace and add the class if we have anything left
          $view_class = trim($view_class);
          if (!empty($view_class)) {
            $variables['classes_array'][] = $view_class . '-container';
          }
        }
      }
    }
  }
}