Using Views Relationships, Arguments, and Attachments

Published July 6, 2009

This article is also available in French from KolossalDrupal.

There's an incredible amount of functionality that can be provided by the Views module, especially when it is combined with intelligent use of Node Reference fields. When you relate your site's nodes with Node Reference fields, these relationships can be easily leveraged to create some very useful views.

I'm going to build a view for a sample music site. In the site, I have 3 related content types for "Band" nodes ("Black Eyed Peas", "Linkin Park", etc...), "Album" nodes ("Back in Black", "Bat Out of Hell", etc...), and "Events" (concerts, television appearances, etc...)

Content Type relationships

Each of these content types has only the minimum fields to demonstrate the Views functionality that is the subject of this article. For example, the "Event" content type doesn't have any location or date fields - they can be easily added at a later time.

To associate the 3 content types, both the "Album" and "Event" content types have a Node Reference field that allow their nodes to point back to a "Band" node. For example, when a new "Album" node is created, the user is forced to select the appropriate "Band".

Album Node Reference Field

In order to make use of these content types, I went ahead and populated several nodes of each type so I have some data to work with when creating the view.

The goal of this article is to be able to create a page that displays a single band node along with all of its albums and events. Here's a quick sample of what I'm aiming for:


Band Info
[Band Name]

Albums
[Album 1]
[Album 2]
[Album 3]

Events
[Event 1]
[Event 2]
[Event 3]

There are several ways to accomplish this - Panels (context) and blocks (visibility) come to mind - but I'm going to use a method that utilizes only Views Attachments. Regardless of the method choosen, it's almost guaranteed that you'd have to create some views so why both with the extra overhead of additional modules and/or code?

A Views Attachment is simply a type of Views Display that gets attached to another View Display (usually a page display or a block display). Simplifying things, it can be thought of like this:

The diagram shows that Page and Block displays (as well as other types of displays defined by other modules) can have any number of attachment displays. These attachment displays can physically appear on the page either before or after the display it is attached to.

For this example, I'm going to create a view that has one Page Display (called "Band Page") and two Attachment Displays (called "Albums Attachment" and "Events Attachments"). The two Attachment Displays will be attached to the bottom of the "Band Page" so we end up with the desired outcome as outlined above.

As usual, you can download all the CCK types and view exports at the end of this article.

For the first step in creating the view, I went to the admin/build/views/add page and created a new node-based View called "band_info" with the following values on the "Defaults" display:

Basic Settings
Title: Band Info
Arguments
Node: Nid ("Action to take if argument is not present: Hide view / Page not found (404)")
Fields
Node: Title
Filter
Published: Yes
Type: Band

Next, I created a new "Page" display and named it "Band Page" and set its path to: "band/%". Remember, the "%" is just a placeholder for the "Node: Nid" argument I set up in the "Defaults" display.

At this point you can save the view and check it out in the "Preview" pane by entering in a valid Node ID for a "Band" node in the argument field. The view should show only the band's name that is associated with the Node ID you provided as the argument.

Now for the interesting stuff. I'm going to create an Attachment display that shows all of the Album nodes for the Band specified by the Node ID in the argument. Remember, there's nothing all that special about Attachment displays. They're just like any other Views Displays except that you can attach them to other displays. To create the "Albums Attachment", I started by selecting "Attachment" from the display select box and clicking the "Add display" button.

Add an attachment display

Initial setup for the new display is straight-forward:

Basic settings
Name: Albums Attachment
Attachment settings
Position: After
Attach to: Band Page

Since this display is going to show a list of "Album" nodes, I want to set the "Node: Type" to "Album". When doing this, I have to be careful not to change the default settings for the entire View - I want to change the settings just for this attachment. To do so, I click to edit the "Node: Type" in the "Filters" section, then click the "Override" button so that I'm only modifying the current display and not the entire view:

Override the Node: Type setting.

Once the setting is overridden, I can then safely change it to "Album" without worrying that I'm messing up the other displays. It is easy to tell when a setting is overridden: it is no longer displayed in italics in the display summary:

Overridden settings

Here comes the tricky part: now that our display is going to show only Album nodes, how do you filter it by the Band's Node ID? With a "Relationship", of course! Remember, the Band and Album content type are related via a Node Reference field. We can utilize that relationship to filter the Album nodes. The first step is to add a new relationship to the "Albums Attachment". In this case, I'm going to add a "Content: Band" relationship. Before I do this, however, I have to ensure that I'm adding this relationship only to the Albums Attachment, not the entire view. This is a common source for mistakes. Take note of the "Relationships" section - notice how it is italicized? That means anything I add to it is actually getting added to the Defaults display - and all of the displays that inherit from it. I first need to click on the "Relationships" link and click the "Override" button.

Override the relationships

Once this is done, I know that I'm safely adding the relationship to only the "Albums Attachment" display. I'm going to add the relationship that links an "Album" node to a "Band" node - in this case, that is the "Content: Band" Node Reference field.

Select the relationship

After adding the relationship, I'm presented with a couple of settings. The "Label" is used only to help identify the relationship as it appears in this particular view. When adding multiple relationships to a view, it is helpful to give them meaningful names. Luckily, Views does a pretty good job at assigning the default, so I'll stick with that.

Select the relationship

In this case, the "Require this relationship" option is not necessary because I know that the argument will filter out all but those Album nodes I want to see.

The final piece of the puzzle has to do with the "Node: Nid" argument. Since the "Albums Attachment" display is inheriting the argument from the "Band Page" display, I have to make sure that it is using it correctly. As it stands now, the display will try to filter the list of Albums with the incoming Node ID argument. This won't do much of anything since the incoming argument is the Node ID of a Band. I need to tell the view to use the argument to filter the Album nodes returned by the Band - using the Relationship I just set up. Turns out this is pretty easy to do.

First off, I need to click to edit the "Node: Nid" argument and then click the "Override" button so that my changes only affect this display. Then, I need to set the "Relationship" select box to "Band". This will effectively filter the Album nodes returned by their associated Band node's ID.

Albums attachment argument relationship

One final thing I did to the attachment to make it a little more user friendly was to override the "Header" setting and add the following:


Albums

This will simply display a nice header above the albums. Taking a quick look at the Preview pane with the appropriate Node ID for a Band, you'll see something like this:

Band page and album attachment preview

At this point, the "Albums Attachment" is just about done. You can add some additional fields, sorts, and display options, but the challenging part is complete.

The "Events Attachment" works exactly the same way. The main difference is that the "Node: Type" filter uses the "Event" content type, but everything else is analagous to the "Albums Attachment" display.

Putting everything together, the final view looks like this:

Final Band Info page

It's not too hard to imagine how you can utilize these tools to generate all sorts of interesting views of this same data. Perhaps an Album or an Event page that shows information from the associated Band node. Maybe add a new content type for "event location", then you can build a view that displays all events by location along with Band information for each event. The method outlined here is flexible enough to allow you to drill as far down into your data as you need.

Comments

ankerek,

if you use the "Node: Title" argument, and make sure you specify the Band relationship, you should be able to get a list of albums by that band.

The PHP code to automatically use the title of the current node would go in the "Provide default argument" > "PHP Code" area.

Submitted by admin on Tue, 08/04/2009 - 09:11

Houston, We Have A Problem.

I tried to do this, but instead of using multiple node-types, I wanted to be able to use one node type. The idea being that I create a gallery, in which there can be other galleries. So, I set up node type gallery, and instead of filtering 'band' i just chose gallery again in the attachment display. This doesnt work. I guess there are some issues if there is only one node type? Any thought much appreciated.

Submitted by dago (not verified) on Wed, 08/05/2009 - 05:52

Spelled my email wrong, this is just so i will see updates :)

Submitted by dago (not verified) on Wed, 08/05/2009 - 05:53

Ok, For some reason I got it to work now. Not sure what happened or where it went wrong... Must have had some setting wrong I guess. Its only a shame that this works only one level deep... Although perhaps there is also something for that? Thats for another time :)

Submitted by dago (not verified) on Wed, 08/05/2009 - 06:54

Struggling with something similar,
I have a content type "Book" that is defined by a node module (hook_node_info etc.), fields in this content type are therefore not shown anywhere (e.g. in Content types>>Manage fields or for views as arguments type).
So how do I create a view which displays nodes of this type which have a particular field (say year_published) value which is passed as argument (e.g. /show_by_year_published / 2009 ).

I guess I need to write php code (which is not a prob) but where do I put it in views.

Thanks in advance,

Submitted by A2Z (not verified) on Wed, 08/12/2009 - 16:43

Author comment

A2Z,

If the "year_published" field isn't exposed to views as a filter, you'll need to use the Views API to add it via a custom module - your best bet would be to just add it to the node module.

-mike

i got a problem with this tutorial. i've made as you wrote about making relationship but next i have no select box to choose in editing node:id argument a band relation (album attachement) any ideas?

Submitted by Guest (not verified) on Sun, 08/16/2009 - 10:10

How to get reverse relationship...I have a content type A which references another content type B..I also have another content type C which also references B..Now I want to display the fields of Content type A and content type C...any ideas??

Perhaps I can elaborate my scenario..I have a content type Track..This hold information about a song track..I have another content type called ringtone which references the track content...I also have another content type called audio..It holds an mp3 for the song track..This also references the track content type..now what I want to do is..I want to list all the ringtones with a link to its corresponding mp3 file..Any suggestions would be appreciated..

Hi,

Very nice article. I tried this for my site to show movie list under actor page.
Content 1: Movie
Content 2: Person
related through actor field.
page path is given as person/%

I used Path auto to create alias. so that the actor "Brad Pitt" will show as
www.mysite/person/23

When i provide 23 to preview option of view page. it is giving the desired result; ie bradpitt's details and list of all movies.

But when I go to the page www.mysite/person/23 it just shows the person content not the view.

Any help?

Submitted by Junk (not verified) on Wed, 08/26/2009 - 15:19

Junk,

I believe you should set the page path as "node/%". When you view the node with the pathauto alias, it should then use the view.

Submitted by dagomar (not verified) on Thu, 08/27/2009 - 02:33

Junk,

What Dagomar said is correct. The "person" content's path is actually node/23 - you could make the view appear in a tab of the node - set the View's path to node/%/movies, and then under Menu choose "menu tab".

if you really really need the node view to contain the view, you could always include it as a block, or use Views Attach. While you can also use Panels, it's really overkill for something like this.

ryanprice ,

thanks for the reply. But if ../person/23 will not work as expected , how is ../drupal6/band/119 working in the above example?

could you please let me know one/two liner description of what menu tab is?

thanks in advance.

Submitted by junk (not verified) on Thu, 08/27/2009 - 15:56

Junk,

In the above example, band/119 is the path to the view, that is, it is not an alias of node/119

Did I mention Views Attach in my previous comment? After reading your questions yesterday, I went ahead an typed up a few Quicktips:
http://drupaleasy.com/quicktips/adding-photos-event-page-views-attach
http://drupaleasy.com/quicktips/showcase-users-comments-views-menu-tabs

These don't answer your questions directly, but they do give examples of Views Attach module and creating Menu Tabs with Views.

First of all, thanks for taking the time to explain this module a little better. It has certainly helped me.

I have to create a departmental site. I have about 13 departments who have similar content, but they can have extra content too. e.g:

Department A
- intro
- news
- staff
- about

Department B
- intro
- news
- staff
- about
- gallery
-----------
I am wondering how to approach this.
The content types I will have to create if I stick to the idea I have are:
-Department
- Intro
- News
- Staff
- About
- Gallery

Then I need to create for each department a department page, e.g: Fishing, Hunting, Food, etc.

Then I create a "About, Introduction, News, Staff, Gallery" content type too.

When creating a "intro page" for your department you need only select your department content type ( i:e Fishing ), likewise when creating a "About" page for the department you are controlling.

Please advise, not 100% whether I am even approaching this in the correct way. Any help would GREATLY be appreciated..

Submitted by Guest (not verified) on Mon, 08/31/2009 - 15:56

Hi

Very interesting article.
But what if the node ref is the other way round. I mean : how do you manage the relationship if the band has a node ref pointing to the album.

I am working on a site where the node ref is "descending" the hierarchy of nodes. Your example is for ascending node refs

Any help would be appreciated

Submitted by Guest (not verified) on Mon, 09/07/2009 - 13:52

ryanprice,

sorry for being too junk :) can u pls let me know how do we set such paths? If we use url alias view will not work and I am not able to find a way to set all person page path to /person/

quote "In the above example, band/119 is the path to the view, that is, it is not an alias of node/119"

Submitted by Guest (not verified) on Wed, 09/09/2009 - 15:00

Thanks so much for this article. I've been struggling with this one to many issue for a few weeks. This makes life MUCH easier! :)

Submitted by Guest (not verified) on Thu, 09/10/2009 - 12:02

#22, I think this really requires a separate tutorial. It's taking too much time to explain in comments. Please use the contact form on the site, and ask your question fresh. I'll see if I can create something that helps.

On the other hand, if you can't wait, I'd be happy to do a screen-share with you if you're willing to buy a little consulting time! :-D

-Ryan

Submitted by admin on Fri, 09/11/2009 - 11:46

Good POST!!!
Thanks, Just what I was looking to solve my problem .-

Submitted by raflebaron (not verified) on Wed, 09/30/2009 - 16:16

views relationships demystified, thanks for this--very clearly written and a great example for content. after beating my head against my desk for a few days, this tutorial got me 90% of where i needed to be. i also needed to do something like show a list of albums in a block on the artist page-as-node. a few more experiments and crossed-finger previews and i figure that out, too (& can document if anyone is stuck). thanks again.

How would I accurately set up a view to reference one content type and display a link to it in another content type?

For example, I have a SERVICES and PROJECTS content type. Under the PROJECTS content type, I have a node reference for all services related to the SERVICES content type. When I select a service from the node reference, I want that PROJECT to display on the SERVICES content type based on the service I chose from the node reference.

Would this tutorial accomplish that? If not, do you know of any resources to do so?

Submitted by Tom (not verified) on Mon, 10/12/2009 - 13:03

Hi Ultimike
First off I'd like to compliment you on a well documented article. It helped me with a similiar feature for my site that I could not find else where. However on the view api where you have to specify the path by using a wild card it works fine, but the problem comes when all nodes point a page with my views name and no content. I am also trying to create another feature using the principle but its also taking me to the same page with the views name and no content. Any ideas why this is happening? the guys in drupal support are reluctant to help. Thanks in advance.

Hello, If the content type "Band" is created by a User with the "Singer" rol, and I want that the View Display show only the Albums that belong to the Bands created by the login User.How I can do this?

Submitted by Isabel Maria (not verified) on Mon, 11/16/2009 - 12:53

Great article! Perfect compliment to my morning coffee. Hoping you might be able to point me in the right direction... I am doing a sports site and I have the usual entities; teams, divisions, seasons, and games. Games are a custom content type with a node reference to teams. Divisions and seasons are simple taxonomies.

I am looking to create a view that shows multiple grid games scores by division.

So division 1 has 10 teams. Each team has 10 games. Each game has a score. (Teams don't play each other so that is not a factor).

I am trying to get a view that shows:

Division 1 Game 1 Game 2
Team A Score: 8 Score: 10 etc ... then total score for the team.
Team B Score: 7 Score: 2 etc ... then total score for the team.

Division 2 Game 1 Game 2
Team C Score: 4 Score: 9 etc ... then total score for the team.
Team D Score: 4 Score: 9 etc ... then total score for the team.

Should I try to use an attachment view or maybe some sort of grouping? Can I make a view this complex?

Thanks,

Schipper.

Hi, I have a question which looks like stupid but I'm begginner in Drupal :
How to do the same thing the other way around?

I would like to create a view of an Album (or Event), and make a link to my Band with the same method.

Thank for your tutorial, it really helps me!

Submitted by Polopollo (not verified) on Wed, 12/09/2009 - 11:48

Hey, Im having a problem i thing this is the answer to but am not really sure :(

Here's the deal;
I need to create a page where people can select different kind of product specifications and eventually get a complete product with the descriptions for those specifications (if that makes any sense).

So i created taxonomy vocabularies with those specs
name vocabulary: wlan
Item 1: 2 (with the description of that option)
Item 2: b (with the description of that option)
item 3: e (with the description of that option)

name vocabulary: gsm
Item 1: 0 (with the description of that option)
Item 2: L (with the description of that option)

now i need to create a page that will show a drop down menu where people can select each option and basically hit submit and get all the descriptions in one row saying for example (wlan)onboard (gsm)N/A

I thought i could somehow do it with the relationships in views but after a few hrs playing with this i'm beginning to doubt that more and more.

there are no content types that use these taxonomys and i should probably mentions that i'm a total noob to all of this :D

Hope you can help, would appreciate it a lot.

In case anyone is looking to "attach" related content in a node.tpl by embedding a block, this works - follow the directions of this tutorial (which is really great) and then put this in your node.tpl file :

<?php print views_embed_view('company', 'block_1', $node->nid);?>

change 'company' to the name of your view, and change 'block_1' accordingly to block id.

Submitted by Guest (not verified) on Fri, 01/15/2010 - 03:17

Thanks a million for the great tutorial! I got it to work with no problems at all.

I've seen some references to pathauto here, which I do use. The problem is I don't have a clue how to modify this demo to base my view on those instead of nids (if that's even possible). I just started working with Drupal so I'm still getting used to it. I'm do know PHP, though, so if that's what I need, it's no problem.

Submitted by Guest (not verified) on Wed, 01/27/2010 - 16:05

I find your article very informative, but like others, I'm having a hard time creating a 3 level deep relationship even though I read your comment to another user with the same problem. A newbie/for dummies walk through would be greatly appreciated!!!

Anyway, thanks for a really great and informative site.

Submitted by Daniel Duvald (not verified) on Sat, 02/27/2010 - 12:19

Excellent introduction (with depth) of Views Attachments, and the only one I've found written by somebody who understands technical writing. There's actually an entire book written on Drupal 6 Views Attachments, but heck, I'm not sure I want to drop 30 or 40 smackers on it.

Submitted by lastar84 (not verified) on Wed, 03/03/2010 - 18:18

Exactly what I needed to read... I was looking for a way to put Project Bid Submissions (tied to Projects using Node Reference field) underneath the Project name in a view and I had never used View Attachments before. Thank you.

Author comment

Thanks for the kind words. I just noticed how many questions there were in the comments to the post! Sorry I can't answer them all.

To answer your question, I believe master-detail views can be accomplished using the "group by" field in the "Style" settings.

-mike

thanks again for the article,
is it possible to show on album page next albums referenced to the band?

example:
band: pink floyd
albums: the wall, the division bell, meddle

on the wall page it shows a link to the division bell and meddle

Hi,
I have a Views question I really need help with. I am creating a jobs board that involves the use of 2 content types - Jobs Postings and Resumes.
When the Recruiter logs in they can see all the jobs they have posted and also see the Resumes that have been posted to particluar jobs. So far everything is working fine as expected.
Now I just have one final thing to complete which is add an option to the Recruiter view that will remove an Applicant from a particluar Jobs Posting or Resume relationship. I only want to clear the entry from the table that the Recruiter sees (ie. Not actually remove the Resume Node itself). Im having terrible trouble trying to work this out. Can you help?

Submitted by Adrian (not verified) on Thu, 05/27/2010 - 09:59

Ajax question:

This is an amazing article, but I will need extra AJAX functions:

Let's say we have a view with a list of several bands - how to show the details of events and albums on the same page when I click on a specific band?

Thanks

Amnon

[...] Dentro de los videos dedicados al módulo Views, extrañé que no se profundizara más en la funcionalidad Relationships. [...]

Mike, this is a PERFECT post! Thank you very much for helping!

I would like to ask you for some help, if you could find a couple of minutes to help... It's nothing too complex, it's similar to your turorial, but a little different.

So, in your tutorial, when you visit a BAND page, you can see all of the band's ALBUMS.

Is it possible to create a similar view, so that when you visit an ALBUM page, to see all the albums of the same band?
For example, in the values you used in your tutorial:
If I click on album "Under the table and dreaming" node, is there any way to have a list of all the band's albums?

Submitted by Drupal_maniac (not verified) on Fri, 11/19/2010 - 17:26

(newbie here)
that was EXACTLY what I was looking for.
I knew there would be a way to avoid the use of Panels and all those extra modules.

One Question:
Is it possible to use something similar to Contemplate to style each part of the combined view?

Excellent post ! Exactly what i'm looking for.
Thanks for sharing !

Submitted by Vincent (not verified) on Sun, 01/30/2011 - 14:09

Hi Ultimike,

Can we have a review system for band/ album/ event content types. Such that users can create reviews for these three content types.

Thanks

Submitted by Subhash (not verified) on Mon, 01/31/2011 - 01:51

What if I have a Views page that aggregates bands from a particular genre say:
/bands/80s

And I want Albums and Events from each. Say:

Duran Duran
[Bio]
[Web Site]
-Albums
--[Album 1]
--[Album 2]


-Events
--[Event 1]
--[Event 2]

Thompson Twins
[Bio]
[Web Site]
-Albums
--[Album 1]
--[Album 2]


-Events
--[Event 1]
--[Event 2]

...etc.

I'm having trouble using Attachments here. Any advice much appreciated.

Thanks,
john

Submitted by j-o-h-n (not verified) on Mon, 04/04/2011 - 14:53

Sign up to receive email notifications of whenever we publish a new blog post or quicktip!

Name
CAPTCHA