Views preprocessors in module files

Fri, Oct 23, 2009 by Rexx

We've all used pre-processors to modify data before it reaches the template file to be printed. These pre-processors are usually defined in template.php with a corresponding template file within the themes folder. The views module is quite helpful because it allows others to use their own themeing files to design their own views.

I was working on a custom node module and wanted to implement views hooks, so that I can expose my tables data to views, and to create default views. Exposing the extra data from my table was relatively simple as I simply implemented the hook: hook_views_data. With this hook, I was able to setup my fields, filters, arguments, and sorting.

So now, with my exposed data ready to be used, I was ready to implement hook_views_default_views. I initially created the views through the user interface and then pasted the exported code in my hook_views_default_views implementation.

After creating the views, I wanted to be able to theme them. In order for me to theme them, I had to override the template files in my themes folder. This is where I thought to myself, what if someone else wanted to use my module? what if it’s not themed as they wanted it to be?
This is when I began searching the web for solutions.
I stumbled upon the views documentation. This is where I found the ability to be able to create views pre-processors in my module file. Here's a snippet that will allow for you to create templates and pre-processors for views in your module:


/**
 * Implementation of hook_theme
 */
function MODULE_NAME_theme($existing, $type, $theme, $path) {
  $themes['views_view_field__field_blog_blogger_nid_nid'] =     array(
    'arguments' => array('view' => NULL, 'field' => NULL, 'row' => NULL),
    'template' => 'views-view-field--field-blog-blogger-nid-nid',
    'path' => $path .'/templates',
    'original hook' => 'views_view_field',
    'preprocess functions' => array(
      'MODULE_NAME_preprocess_views_view_field__field_blog_blogger_nid_nid',
    ),
  );
  return $themes;
}

The arguments must be correct or else you'll see huge errors. To check what the arguments are just look at the original theme hook, in my case theme_views_view_field. After creating the file and preprocess function, clear the cache and the preprocess function should be executed. Here's a link to more help about using default views and themeing them in your own module. http://views-help.doc.logrus.com/help/views/api-default-views.

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