Using default arguments to relate nodes by their common taxonomy terms

Given a list of videos tagged with a specific vocabulary, I wanted to show a view of these videos on the page of another node type (a "channel") that is also tagged with the same vocabulary. The idea is to create video channels that implicitly relate to videos by sharing taxonomy terms, instead of explicitly relating the videos to their channel (using node references for example). The videos should show on the channel's node page. The problem from a Views perspective is that no field in the video node points to the channel node, so how to relate them in the view?

[graphviz] digraph G { Video -> Topics; Channel -> Topics; Video [shape=box]; Channel [shape=box]; Topics [shape=ellipse]; } [/graphviz]

Here's my solution, using default arguments in the view:

  • Since we're showing the view on a node page, the URL will give contain the nid argument. However, we don't want to filter the query using this argument, so add a Global: Null argument to silently bypass the argument.

  • Add a second argument of type Taxonomy: Term ID. This argument is guaranteed NOT to exist on the URL (since we're dealing with node/%nid). So we configure this argument to "Provide default argument" > "PHP Code" where the code is:

<?php
$channel
= node_load(arg(1));
return
implode('+', array_keys($channel->taxonomy));
?>

and we "Allow multiple terms per argument".

  • Add a Viewfield CCK field to the channel where the forced, default view is the once created above.

That's it! As per dereine's comment below, you can find a patch for Views that accomplishes what's described here.

Comments

Thanks!

As someone on Views2 without an ability to swap to a dev release of 3.0, this PHP default argument just made my day. I've been trying to find a way around this issue for a week!! Thanks ever so much for posting it. -kgb

Benefits

Very nice! Thanks!

What do you see as advantage(s) of using taxonomy over node references in this way? A better interface for the end user? Performance? Ease of setup?

The benefits are less manual

The benefits are less manual work for the site editor, and less complexity/redundancy in the data model for the site builder. I am assuming that the taxonomy would already be in place for videos, which was true in my case.

<?php$channel =

<?php
$channel
= menu_get_object();
return
implode('+', array_keys($channel->taxonomy));
?>

This code does exact the same, but it safes a function call.

There is also a patch which adds a default argument plugin to views, which is always the better way to do it: http://drupal.org/node/684608

Thanks for pointing to the

Thanks for pointing to the patch, it saves me writing one :-)