Over-riding Views 2 Output in Drupal

Tue, Jul 14, 2009 by Rexx

I have been using Views 2 module a lot lately and the more I use it, the more I appreciate its elegantly designed architecture. It is very powerful and flexible. Popular modules such as Organic Groups and Location make the Views 2 module even more powerful. Showing information to end-users becomes easier when you want to show certain group posts or perhaps display the list of members of a group given a certain location.

I believe that the biggest factor which contributed to the popularity of Views 2 is its flexibility. You can pretty much override everything, from overriding its query using hook_views_query_alter(...), to being able to override its output at a very granular level(field result level).

Let's say that you want to show a yearly sales report of your 5 departments highlighting the sales per month. You can assume that a “department” is implemented as a node. Your have created a “Page” display of your View. The style of your View is set to “Table”. You have selected “Node:Title” as your department's name.

Here I will show you step by step process on how to override the result of a Views query.

1. Click “Theme:Information” under you Views “Basic settings”.
2. Override the table template by creating “views-view-table—name-of-your-view--page.tpl.php” file in your themes folder. (You will see this beside “Style output:” option)
3. Click “Style output:” and copy the code and paste it on the template file that you just created.
4. Click the “Rescan template files” button and then click “ok”.
5. Implement the template files preprocessing function and name it “[your_theme_name]_preprocess_views_view_table__name_of_your_view__page”. It should accept a reference of an associated array “&vars”(you can name it “Bob” if you want)
6. Clear your cache.

Now that you have the all the ingredients for your report, it is time to get our hands dirty. The variable that will be passed to your preprocessing function contains an array of table headers, rows and the views object, which contains an array of result objects of the view. Since the variable is passed by reference, you are free to do whatever you want as long as you maintain the structure of the headers and rows of the view. You can also use the result of the query to extract the sales for each month given the department id.

The pseudo code below will show step by step how we can accomplish our goal.


function theme_name_preprocess_views_view_table__sales_report_view__page(&vars) {

  // table headers to append to the existing headers, respect the  structure of table headers
  $months = array(
     'month_1' = t('January'),
     'month_2' = t('February'),
     ...
     'month_12' = t('December'),
  );

  //your table headers is an array associative array keyed by your chosen field and the value is the label
  //value that you set
  array_merge($vars['headers'], $months);

  //you can think of $result as the raw version of the $vars['rows']
  $result = $vars['view']->result;
  $nids = array();

  // get nids for custom query processing
  foreach($result as $k $res) {
    //department id  
    $nids[] = $res->nid;  
  }
  /*
    This block of code should extract the sales for each month given the
    department ids.
    Assume that $sales is an array of sales data keyed by the department id
    $sales = array(
      'department_id' => array(
        'month_1' => $111.00,
         ...
      ),
      ...
    );
   */
  $sales = get_sales($nids);

  //finally!!! process the result
  foreach($vars['rows'] as $k => $row) {
    // the views result is arranged in the same order as the $vars['rows']
    $nid = $result[$k]->nid;
    // add the sales for each month
    array_merge($vars['rows'][$k], $sales[$nid]);
  }

}

Views V.S. Custom Query

Some people would say that custom query runs faster than executing this view. Although I haven't done benchmarking, they may be correct. However, what if the client wants a full blown reports page in which they can filter reports and have the option to export the result in a csv file. Maybe custom query and code will save some processing time, but solving a problem like this using Views will save your company money by increasing your productivity. Take advantage of what Views has to offer before implementing your own custom code.

Tom posted on May 25, 2010 1:33 pm

How would you best modify a views output for a given node?

macsoftware posted on December 28, 2009 8:48 pm

It is about views2 theming but doing with preprocess.
This is interesting, i have never done this.

Anonymous posted on December 15, 2009 1:03 am

This doesn't work any way I have tried it. Just get PHP errors.

autostan.kz posted on October 25, 2009 10:39 am

it's ok, but it is dificult to change view-page title:
if we change it in the *.tpl file (via drupal_set_title), it's look OK, but when view output is taken from cache (devel: cached output), title didn't change from default

admin posted on July 14, 2009 9:39 pm

Yeh. This has been fixed.

Arnold

Benjamin Melançon posted on July 14, 2009 7:56 pm

The title is misleading-- this article isn't about overriding Views queries (such as to optimize a query but keep all the surrounding functionality Views offers), but rather about theming a View.

ben, agaric

Post new comment

The content of this field is kept private and will not be shown publicly.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd> <img> <h2>
  • Lines and paragraphs break automatically.

More information about formatting options