Styling whole rows by taxonomy: overriding handlers

Last modified: October 28, 2008 - 14:50

This approach works for getting any kind of data from individual fields out to the whole row (or list item in a list view). There's all sorts of things you can do with handlers.

Step 1: Override your view's theme.

For a table view, copy the stub from the Views theming handbook page. Then replace the field loop as follows:

<?php
foreach ($view->field as $field) {
  if (
$fields[$field['id']]['visible'] !== FALSE) {

   
// Special handling for the taxonomy field: set a row class based on term
   
$vid = 1; // Your vocabulary ID

   
if ($field['tablename'] == 'term_node_'. $vid) {

     
// Impose our own handler
     
$field['handler'] = '_mytheme_views_handler_field_allterms';

     
// get both data and term ids from our handler
     
list($cell['data'], $tids) = views_theme_field('views_handle_field', $field['queryname'], $fields, $field, $node, $view);
     
$cell['class'] = 'view-field '. views_css_safe('view-field-'. $field['queryname']);
     
$row['data'][] = $cell;
     
     
// Add a row class based on the term ID
      // Assume $tids has only one entry: current vocabulary is single-term. TODO: Rewrite this to handle multiple terms
     
$row['class'] = 'custom-class-'. $tids[0];
    }

   
// All other fields
   
else {
     
$cell['data'] = views_theme_field('views_handle_field', $field['queryname'], $fields, $field, $node, $view);
     
$cell['class'] = "view-field ". views_css_safe('view-field-'. $field['queryname']);
     
$row['data'][] = $cell;
    }
  }
}
$rows[] = $row;
?>

What we've done here:

  • Added our own function as a handler to the field
  • Changed what we expect to get back from the handler: in this case, not just data but also an array of term IDs.

Step 2: Copy the handler function you're overriding and adapt the code to your needs.

In this particular case:

<?php
function _mytheme_views_handler_field_allterms($fieldinfo, $fielddata, $value, $data) {
  if (
$fieldinfo['vocabulary']) {
   
$terms = taxonomy_node_get_terms_by_vocabulary($data->nid, $fieldinfo['vocabulary']);
  }
  else {
   
$terms = taxonomy_node_get_terms($data->nid);
  }
 
// Store the term IDs
 
$tids = array_keys($terms);

  if (
$fielddata['options'] == 'nolink') {
    foreach (
$terms as $term) {
     
$links[] = check_plain($term->name);
    }
   
$links = !empty($links) ? implode(' | ', $links) : '';
  }
  else {
   
$node = new stdClass();
   
$node->taxonomy = $terms;
   
$links = theme('links', taxonomy_link('taxonomy terms', $node));
  }
  return array(
$links, $tids);
}
?>

 
 

Drupal is a registered trademark of Dries Buytaert.