JuliaKM.com

Adding to $items in a Drupal view

March 17, 2008

I recently needed to add an extra link to the end of my $items list in a list view and found that this could be done quickly in template.php.

I set out to do two things:
- add a link to the end of my list view that does not contain node data
- as part of this last list item, include a custom link that changes depending on the name of the view

Accomplishing this was a lot easier than I expected. All I had to do was add a switch statement for the view name, and also add a line with the content I wanted to add to my $items array before the theming function.

Here is my code:

<?php
function phptemplate_views_view_list_myview($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['fullNode'] = node_load($node->nid);
   
$vars['link'] = l($vars['fullNode']->body, 'node/' . $node->nid);
   
$vars['count'] = $i;
   
$vars['stripe'] = $i % 2 ? 'even' : 'odd';

//adding extra variable for view name contextual links, in a template, this will be $linked_page.
   
switch ($vars['view']->name) {
    case
'view_one':
       
$vars['linked_page'] = '/news/special_one';
        break;

    case
'view_two':
       
$vars['linked_page'] = '/news/special_two';
        break;
       
    case
'view_three':
       
$vars['linked_page'] = '/news/special_three';
        break;   
       
    case
'view_four':
       
$vars['linked_page'] = '/news/special_four';
        break;
                       
}
    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'])) {
       
$vars[$name . '_label'] = $field['label'];
      }
    }
   
$items[] = _phptemplate_callback('views-happy_news', $vars);
  }
//the key, I'm adding a link to the $items[] array.
   
$items[] =  "<a href=\"{$vars['linked_page']}\" class=\"more-articles\">See more news</a> »";
  if (
$items) {
    return
theme('item_list', $items);
}
}
?>

Thanks

Wed, 04/23/2008 - 15:43
Rostyslav (not verified)

man i was looking for this all this week...
At last i found it...
Thanks a lot :D