There have been several occasions when I’ve been working on a Drupal view and needed some conditional logic when re-writing the output of a field. It would be nice if there were some kind of built-in IF or SWITCH statement, but there’s not. On my latest project, I decided to consult Google for some Drupal wisdom.
The result was the Drupal Views Custom Field module. It basically adds three new field types that you can display in your view: Markup, PHP Code, and Rownumber. While I’m sure that Markup and Rownumber can be really useful, I didn’t investigate them at this time. I mainly wanted the functionality provided by the PHP field type.
The main problem I was trying to solve was that I needed to display a different link depending on the node type. I was pulling in feed items from another site and mixing those with internal blog entries. If the node was a feed item, I wanted to link to the external blog page. If it was a blog entry, I wanted to link to it’s node in the current site. Even with the custom field module, I struggled a bit. To begin with, I was trying to exclude all other fields from display and write the entire row of content into a single PHP field. The downside of doing it that way is that you forfeit several build-in Drupal functions for path aliases, date formats, and others.
My next approach was to use a PHP field to calculate the link, and then use normal view fields to pull that content in and display it. This worked better, but I still found some instances where I needed to calculate a path alias. I eventually found that I could wrap a node ID with the “drupal_get_path_alias()” function and Drupal would handle the rest for me. I suspect that there are several other drupal functions that I’ll be able to incorporate when I use this technique in the future.
Maybe future releases of Drupal views will have a facility for conditional logic. Until then, I’ll be using the Views Custom Field module to achieve similar results.