Drupal 6, theming views: preprocess functions

I couldn’t find this documented anywhere – the most useful thing on drupal.org is this thread http://drupal.org/node/303586 – and in fact only worked it out by just trying random things until they worked, so (as with all of the other Drupal posts) I am documenting it here for posterity.

If you want to do something like show a certain value in a certain field in your list-formatted view depending on what is in another field in the same row, (so for example, a download link or an ’email author for copy of document’ link, depending on the third cck field (do you prefer people to download this document or email the author), then you might want to do this using theme level preprocess functions. Preprocess functions allow you to manipulate data more easily than you would be able to in the template file itself. Well, it certainly looks neater anyway.

I’m using the zen theme, so keep in mind that the way this works might have something to do with that. You first have to create a .tpl.php named corresponding to the function you want to override:

  1. Go to /admin/build/views/edit/[yourviewname]
  2. Click on whichever view display you wish and under basic settings click on ‘Theme information’. This gives you a hierarchy of template name overrides for your views.
  3. Make a note of the last template name suggestion in either the style output or the row style output. So if you decided to override the row style output and your view is called ‘documents’, and your display is ‘page 1’, the template name you choose will be views-view-fields–documents–page-1.tpl.php
  4. Go to the views module folder and in the theme subfolder copy the template with the first name in the hierarchy that you chose in the previous point. In the previous example it would be views-view-fields.tpl.php. This needs to go into your theme’s directory, and if you’re using zen it seems to go into [yourthemename]/templates

Remember to clear your theme cache once you have done this! This is very useful anyway, as you can now change the tpl.php however you want to. But if you want to preprocess the data before it enters the template, you need to create a function in your theme’s template.php named like this: [yourthemename]_preprocess_[the name of the views template you copied with – changed to _].tpl.php. So in the previous example, it would be function mytheme_preprocess_views_view_fields__documents__page_1(&$vars) {}.

I don’t know how these preprocess functions work, it might very well have something to do with zen registering some views preprocess functions for you, but it does work and it’s very useful and finding info about it on the internet was a bit of a mission for me.

Leave a Reply

Your email address will not be published. Required fields are marked *