fromMarch 2013
Article:

Views Rewrites

Making Fields Do What They Don't Do
0

If you've spent any time with Drupal, you've heard of — and likely installed — the Views module. If you haven't, then you're very likely working harder than you need to! Views is Drupal's query builder, enabling you to create lists of just about anything, as well as providing basic formatting and the ability to do basic formatting of your items. Although Views will be merged into Drupal 8, if you've never used it before, take a look.

Since most Drupal designers have used Views, they generally know its power: Yes, it will relate data to other data, sort, filter, and so on. But one very helpful feature neophytes may not have discovered is its ability to rewrite fields. In essence, a field can be added to the display, but in the settings for that field you have the option to “rewrite” that field; it will keep the settings of that field, but will masquerade as something else: it can be changed to plain text, to a link, or even to another field entirely. Here, we’ll walk you through some examples, and then talk about other options this feature offers.

Why would I do that?

There are plenty of reasons: your field may not contain all the data you want; it might have too much data; it might not have all the settings you want or behave in the way you need. However, some other field just might accomplish those chores. Read on.

Rewriting Content: Title

Let's say you want a simple view that contains a bunch of images, and you want those images to link back to the node. You only want the images and perhaps some related data, like the user who posted the image. Drupal nodes all need a title, but in this case you don't want to show it in the view: first, create a content view. In your view display (page, pane, or even the master, if you want), you add the fields Content: Title, Content: Image (whatever the name of your image field is), and User: Name.

“But wait!” you protest, “I thought we didn't want Content: Title to show.” That’s true, but we still need it in order to link the image to its original node. In Views 7.x-3.x, Content: Title is the only field with the ability to link easily back to its original piece of content. This is where the power of rewriting fields comes in. When you're looking at the fields you've added, they need to be in a particular order. Rewrite Content: Title to be Content: Image. To do that, the Content: Image field needs to be above Content: Title in the field list. Use the 'up/down' button in the 'fields' title bar if items are out of order.

With Content: Image at the top, you can start changing field settings to get the desired effect. Click on the settings for Content: Image. There are two important things to do here: set your image formatter so that it looks right, then exclude the field from the view using the checkbox. I know that sounds counterintuitive, but trust me! Next, open the settings for Content: Title. Then check the box for 'link this field back to its node'. Then scroll down to 'rewrite results' and open up that fieldset. Choose the box 'rewrite results for this field'. Scroll down a bit in the modal to find a list of substitutions; open this up to find what you need. In this list there should be something that looks like [field_content_image] - Content: Image. Copy the section with brackets — include the brackets! — and paste it into the text box above to rewrite the field.

Views Replacement Patterns

The image data will be passed down to the Content: Title field, keeping its formatting data, but now it's also wrapped in the formatting of the title field so it links back to its original node. It might seem complicated, but its fairly simple once you've tried it a few times.

That Was Pretty Easy, Can I Do Something More Complex?

You can go downright crazy rewriting fields. You may want a field to show only if other fields have a result. For instance, take the above example, but now let’s say you want to show that users are talking about it in the node's comments, but only if there are comments. Also, let’s say you want to show more information about the content and comment authors, like their real names instead of their Drupal usernames. Those things are all possible, but they require a slightly more complicated view and a lot more field rewriting.

You can start with the items in the first example, so you already have some of the node content. Because this is a Content-based view, it won't have the user's profile information immediately available for the author or for the commenters. For those fields to become available in the "Add fields" section of the Views UI, you need to relate that data somehow. This is accomplished by using Views Relationships.

Under the Advanced link, you'll find a whole new set of items that Views uses to add or filter information, along with a lot of other things. Once you've used this more than once or twice, you're almost certainly better off going to the Views list page, then the Settings page, and choosing the option "Always open Advanced settings". Most Views users use these regularly enough that keeping it open in every case saves a few clicks.

In this group, you will find the Relationship section. Adding relationships works just like adding fields; the tricky part is figuring out which relationship will bring in the data you need, and sometimes you need one relationship to get to another relationship that actually has what you're looking for. Each available relationship has a one-line description of what it's supposed to be giving you. Here's a look at some of the User relationships available to a Content view.

Views User Relationships

Now we want to bring in the actual user's name instead of their site username. Assuming that the user profile has those fields defined (because they aren't in stock Drupal), adding the Content: Author relationship will make all the fields in the user profile available to the Add Fields section of Views. If you go back there and choose the + sign to add a field, you can filter to "User", and you should see the value for your user's real name field.

Views User Real Name

If you want to do the same thing for comments, you can accomplish the same task by using the Comment: Author relationship.

Here’s where things start to get a little nuts; we’ve stipulated that we only want comment fields to show if there are comments — especially if we’re using a link to the comments. If there are no comments on a piece of content, and you add comment fields to your view, Views will use information from the author of the node. This can be confusing and look totally wrong.

Here’s what you do:

First, add all the fields that you wanted to use anyway. Add the name field or fields, making sure that they’re configured based on the correct relationship. (In the settings for the field, the Relationship box should say “Comment author” or something similar.) You can also add ‘Comment: Rendered comment’ to get the comment text. This gives you the base from which to build rewrites.

There’s one field we can rely on to tell us if there are comments or not: Content: Comment count. This field is a straight up number of comments, where zero means no comments have been left. Because this field uses a count, it also contains a pair of important settings:

No Results Behavior Settings

When you look under No Results Behavior, you can see that you can tell the Comment Count field to pronounce 0 (no comments) as empty — you can then hide that empty field, which solves the pesky problem noted earlier about using the node data if the comment data is empty.

We are going to use the Comment Count field several times. Each time that you need to add a field related to comments, rewriting it is the key. Unfortunately, you can’t add multiple instances of the same field at once, so every time you want to use this field you’ll have to add it in again via the “+” symbol. Add the field once, and in the configurations screen, choose "Rewrite results". The same fieldset you saw before will open, and you'll want to change several of these to get the right effect. This means that for every field related to comments, you need to add a new version of the Comment Count field and rewrite it.

Down in the Replacement patterns there are several more options. You should have a rewritten field for every original field you already added. If you don't see the field you expect, make sure the field you're going to substitute in is above the field you're rewriting in the Fields list! This can especially be a problem if you know you're going to be rewriting fields; simply add the field in at the same time as the fields you're getting data from.

In our example, we are using both the real name of the content author and the comment author. This is another area to pay close attention to — this field is named the same, even though it's being used for different things, differentiated by an _1 in the repeated instance. In this case, you might have [field_realname] for the content author, and then [field_realname_1] for the comment author.

Comment Author Settings

In this image, we’re using the Last Comment Author relationship to add the Comment author’s first name, last name, and picture. Each of these fields is hidden; the Comment Count field is then added and rewritten. It’s a really good idea to add an Administrative Title to the rewritten field as well — look in the field configuration under More. In the image, you can see that’s been done, so it’s easy to tell that the rewritten fields show first name, last name, and picture instead of having Comment count three times.

Other Things Rewrites Can Do

Rewrites can send you to a particular link. They can forcibly trim a field to a particular number of characters, which is useful if you want to create your own teaser, or only show a certain number of characters in a person’s name while maintaining the integrity of the data. (You could show John D instead of John Doe, without needing CSS or an extra field.)

Rewrites will strip HTML tags — maybe you don’t want anything wrapping this field in particular. You can choose to preserve some tags. For example, if you’ve pre-formatted some text, you can choose to keep the

and
tags so that your formatting remains intact, while stripping any other internal link tags or whatever else might be in there.

Rewrites won’t clean your fridge, but it will clean up whitespace for you. It will also change newlines to breaks, so that your formatting is (again) cleaned up and at least close to what you intended originally.

Another thing rewrites won’t do for you is allow you to use PHP in the rewrite: It is HTML only. If you want custom PHP, it’s bad practice to stick it in through the UI. There are modules available that can help you do that, Views PHP (http://drupal.org/project/views_php) being the most prominent. In general though, it’s a better idea to use templates and be mindful of how and where you’re using PHP in or with Views.

Remember, rewrites are your friend. Add your original fields first. Format them. Then, and only then, work with your rewrite tokens. You’ll be able to accomplish all kinds of things!

Advertisement

From our blog

Entity Storage, the Drupal 8 Way

In Drupal 7 the Field API introduced the concept of swappable field storage.

The Drupal 6 to 8 Upgrade Challenge - Part 2

Having concluded the readiness assessment, we turn next to migrating the content and configuration. In reality, there’s little chance that we would migrate anything but the blogs from our old site. For the sake of giving Migrate in Core a workout with real conditions, however, we’re going to upgrade with core’s Migrate Drupal module rather than rebuilding.

The Drupal 6 to 8 Upgrade Challenge - Part 1

Nathaniel Catchpole , the Drupal 8 release maintainer and Tag1 Senior Performance Engineer, suggested that Drupal shops everywhere could support the

DrupalCon Austin

The entertainment industry is not for the faint of heart.

Drupal Watchdog Joins the Linux New Media Family
Drupal Watchdog 6.01 is the first issue published by Linux New Media.

Drupal Watchdog 6.01 is the first issue published by Linux New Media. Come see the Drupal Watchdog team at DrupalCon 2016!

Drupal Watchdog was founded in 2011 by Tag1 Consulting as a resource for the Drupal community to share news and information. Now in its sixth year, Drupal Watchdog is ready to expand to meet the needs of this growing community.

Drupal Watchdog will now be published by Linux New Media, aptly described as the Pulse of Open Source.

Welcome to DrupalCon Barcelona - The Director's Cut

For all you schedule-challenged CEOs – and ADHD coders – this Abbreviated Official Director’s Cut is just what the doctor ordered.

Welcome to DrupalCon - The Barcelona Edition

Did we have fun in Barcelona?
OMG, yes!

Did we eat all the tapas on the menu and wash them down with pitchers of sangria?
Yes indeed!

Recursive Closures and How to Get Rid of Them

This came up while manipulating taxonomy children and their children recursively, so it’s as not far from Drupal as you’d think.