Tuesday, October 2, 2012

Views Attachment in Drupal 7

I've seen answered a few questions on Stackoverflow and the Drupal StackExchange on creating a View with attachment.  Here's how to do it in Drupal 7....

When to use a Views Attachment

Perhaps you'd like to show a block of a particular type of content like News in a side bar of your webpage.  You already know that you can easily create a list of the top 5 News items (title only) using Views.  But what if you want the first News item to show the news article image in addition to the title?

Or perhaps you want to display a list of your blog posts and for the first 2 posts, you want to show the title and a summary.  But you also want to list the title of another 4 posts below that.  

This is where Views attachment comes in.  With Views attachment, you can create one View display and attach a another View display with different configuration (eg. different fields of the content type displayed).  And you can refer to both displays using the one View.

Breakdown of one block created using Views with an Attachment display.

Creating a View with an Attachment

I assume you know how to create a basic View so I'll skip the step-by-step of creating the initial View.  Here's what my initial block View might look like.  Note that I'm only showing the Title of my News article and I've set the view to skip the first News article (Pager options' Offset = 1) because I want to show the first article a little differently.

Now, when you add a new display to this View, notice that you have the option of creating an Attachment.  Let's add an Attachment.

In the Attachment display, I can now configure a different set of fields to display, not forgetting to apply the changes only to the Attachment display as not to affect the original display I created.

Add the image field ONLY to this Attachment display.

The Image field added.

Notice that the middle column of your Views display settings are the Attachment settings.  For the Attachment that I created above, I've set it to attach to the Block which I created initially and I've set the Attachment to be positioned before the block because I want the News item with the Image displayed first, on the top.

I've also set the the Pager settings to only display one item.  Remember in the Block display, I set the offset to 1 in order to exclude the first item from the Block. This is where I'm going to display the first item with an Image.

Now, if we save the View created above, you should get one Block that you can place in your site which contains both News listings with an Image and a title and News listings with just the title like this....

ONE block with two displays
one display with image and title
and  one display of title only.

Note that there are likely other ways of achieving the same thing.  For further reading, see: