Group views with header by date

Last modified: March 30, 2008 - 14:26

I've come up with a cool variation on this snippet that allows you to group nodes by a date field. I've used it to create a news clipping archive that's sorted and grouped by the year that the clips were published.

To do this, I created a CCK node type called "News Clipping" and created a "Print Date" using CCK's associated date module. So, every clipping node has a custom date field that's available to the views module. In my custom view, I've given the print_date field the label "Date" - you'll need to change that to whatever you want in the view.

Here's the code:

<?php
function phptemplate_views_view_list_palm_in_print_by_year($view, $nodes, $type) {
 
$fields = _views_get_fields();

 
$taken = array();

 
// Set up the fields in nicely named chunks.
 
foreach ($view->field as $id => $field) {
   
$field_name = $field['field'];
    if (isset(
$taken[$field_name])) {
     
$field_name = $field['queryname'];
    }
   
$taken[$field_name] = true;
   
$field_names[$id] = $field_name;
  }

 
// Set up some variables that won't change.
 
$base_vars = array(
   
'view' => $view,
   
'view_type' => $type,
  );

  foreach (
$nodes as $i => $node) {
   
$vars = $base_vars;
   
$vars['node'] = $node;
   
$vars['count'] = $i;
   
$vars['stripe'] = $i % 2 ? 'even' : 'odd';
    foreach (
$view->field as $id => $field) {
     
$name = $field_names[$id];
     
$vars[$name] = views_theme_field('views_handle_field', $field['queryname'], $fields, $field, $node, $view);
      if (isset(
$field['label'])) {
        if (
$field['label'] == 'Date') {
          if (
$header != date("Y", strtotime($vars[$name]))) {
           
$new_header = date("Y", strtotime($vars[$name]));
          }
        }
        else {
         
$vars[$name . '_label'] = $field['label'];
        }
      }

      if (
$new_header) {
        if (
$items) {
         
$main_items[] = theme('item_list', $items, $header);
        }

     
// reset values for the next one.
     
$items = array();
     
$header = $new_header;
     
$new_header = '';
      }
    }

   
$items[] = _phptemplate_callback('views-list-palm_in_print_by_year', $vars);
  }
  if (
$items) {
   
$main_items[] = theme('item_list', $items, $header);
  }
  if (
$items) {
    return
theme('item_list', $main_items);
  }
}
?>

**Note the use of strtotime and date functions to create the correct header.

 
 

Drupal is a registered trademark of Dries Buytaert.