Upgrade Your Drupal Skills

We trained 1,000+ Drupal Developers over the last decade.

See Advanced Courses NAH, I know Enough

Views "rewrite output" and you wish you had PHP? Don't always resort to customfield!

Parent Feed: 

First of all, let me tell you how much I love and appreciate the Views_Customfield module, which lets you (among other things), write PHP to print out a field using views. When I need to, I can do some complex conditional-writing based on two other views fields, or I can do things like calculate a thumbnail for a photo gallery based on grabbing some fields using a raw db_query that aren't available through views, and other such craziness (note: be wary of doing this it can kill your site performance!).

But I've found that I can be quick to download and install that little gem in cases where I don't really need it. Take today, for example.

I was building a table view and I wanted the second column to be a concatenation of three fields. In an ideal world, it would look something like this:

Chris Wells (Redfin Solutions)

The three fields are first name, last name, and business name. Business name is an optional field, though. I needed the parentheses around it to offset it, I mean "Chris Wells Redfin Solutions" would in fact look pretty unclear, if not downright silly.

So I thought, well, I will exclude the business name and first name fields, and then I will write the last name field to be (paraphrasing):

[first] [last] ([business])

...by using tokens and the "rewrite the output of this field" piece of Views. The problem here, though, is that when you write that, and business is blank (remember, it's an optional field), you get bogus parentheses, like "Chris Wells ()" which also looks kinda silly.

Here's the trick. All you need to do is doubly-rewrite. Go to the business name, and rewrite it, putting parentheses around it. Then check "hide field if empty." Also mark "exclude from display."

Then, in your later field, you can use the token for the business field WITHOUT wrapping it in parentheses, et voila! A field that only writes (including the parentheses) when there is content in it. No need for PHP, Views is already working hard for you.

Author: 
Original Post: 

About Drupal Sun

Drupal Sun is an Evolving Web project. It allows you to:

  • Do full-text search on all the articles in Drupal Planet (thanks to Apache Solr)
  • Facet based on tags, author, or feed
  • Flip through articles quickly (with j/k or arrow keys) to find what you're interested in
  • View the entire article text inline, or in the context of the site where it was created

See the blog post at Evolving Web

Evolving Web