User login

Using the taxonomy term associated with a node as an argument in a view

How to in Views 2

Using a taxonomy term associated with a node as the argument in your block view. In the original Views module, the PHP Argument handling code was a collapsed fieldset that opened to reveal a textarea in which to input code. In Views 2 this is still necessary, unless we're missing out on some uber-advanced method, but harder to get to.

We are certain it must exist though:
"Block displays have no source of arguments at all; they cannot pull arguments from the URL, and often require use of the PHP code default in order to get arguments."
- from http://views-help.doc.logrus.com/help/views/argument

OK, so if you go to "Action to take if argument is not present: "

and select "Provide default argument"

A div appears below:

"Provide default argument options"

select "PHP Code"

and there, below, will AJAX-ily appear our box for entering code.

and we're back in business, because we have a code box, where we can make it work.

Here is the code that worked for us in Views 2, leave off the php tags when putting it in the box:

<?php
if ((arg(0) == 'node') && (is_numeric(arg(1)))) {
  $industry_node = node_load(arg(1));
  $tids = array_keys($industry_node->nat);
// this will only work correctly when the single term associated with an industry node is its industry term
// which is a reasonable assumption for node auto term
  return $tids[0];
}
?>

Note: Do not, I repeat, do not (Dan, do I have your attention) do not check off the PHP Code under Validator options unless you actually intend to use PHP code to validate and return TRUE. Leaving the code area blank will always result in your lovely argument code above failing validation. Have a good day.

Views 1 Drupal 5 approach

We did it here first, the above Views 2 solution is derived from this.

Plumbing the depths of a big brain dump on Views arguments, nodes' taxonomy, and context for Drupal 5 Agaric comes across this in our own notes:

<?php
if ((arg(0) == 'node') && (is_numeric(arg(1)))) {
  $industry_node = node_load(arg(1));
  $tids = array_keys($industry_node->taxonomy);
  // this will only work correctly when the single term associated with an industry node is its industry term
  $args[0] = $tids[0];
}
?>

Note that the <?php tags are for formatting and indicating PHP code here-- do not use that part in the views argument handling code textbox.

(A fun stop along the way, I'd left off that last line:
"um, make sure there's a closing }
the whole thing was evaluating to a parse error i'm sure which is why nothing did anything")

no hey though
12:52
this is what I put in
if ((arg(0) == 'node') && (is_numeric(arg(1)))) {
$node = node_load(arg(1));
$tids = array_keys($node->taxonomy);
// this will only work correctly when the single term associated with a node is its term
$args = $tids;
drupal_set_message('

'. var_export($node,TRUE) .'

');
print("Hey");
print_r('

'. var_export($node,TRUE) .'

');
}

ok, good to know that the prints don't print out anywhere when called that deep in the internals of views

The drupal_set_message does though:

<?php
   'taxonomy' =>
  array (
    3 =>
    stdClass::__set_state(array(
       'tid' => '3',
       'vid' => '1',
       'name' => 'Information Technology',
       'description' => '',
       'weight' => '0',
    )),
  ),
?>

<?php
if ((arg(0) == 'node') && (is_numeric(arg(1)))) {?$node = node_load(arg(1));?$tids = array_keys($node->taxonomy);?// this will only work correctly when the single term associated with a node is its term?$args[0] = $tids[0];?return $tids[0];?}
?>

Exercise for the reader:
experiment with return implode(',', $tids)
and one of the settings that expects multiple terms in the argument

Providing a default default

(I think we're back in Views2 land.)

Note: the cool thing about this view is that it's providing a banner graphic across the top of the page based on the taxonomy term to which a the node being viewed belongs and to which an image node also belongs. That'll help explain this question.

Dan:
if the node you're on isn't tagged to any term, then you get nothing... any way to have a default fallback graphic?

or just do a background bg on the div?

the div background would be easy, but a better code solution would be cooler

Benjamin Melançon:
well, you could hardcode in a taxonomy term if none come up, but that gets hard if you have to filter by vocabulary and such
how hard would it be to make the "empty text" look just like the view output, and tell it to use that?

hmm, filtering by vocabulary, and if there's nothing in the vocabulary, using the term of your choice, might be better

that would sort of solve both problems
be able to return a single value
you could/should also make the vocabulary required, have a default, and only be able to select one

But no, Dan wanted multiple select. All right, bust out the super-robust randomizing term selection code!

<?php
if ((arg(0) == 'node') && (is_numeric(arg(1)))) {
  // define constants here for convenience:
  $vid = 1;
  $default_tid = 1;
  // get our node, which includes any taxonomy terms it has
  $node = node_load(arg(1));
  $tids = array();
  foreach ($node->taxonomy AS $tid => $term) {
    if ($term->vid == $vid) {
      $tids[] = $tid;
    }
  }
  $count = array_count($tids);
  if (!$count)  return $default_tid;
  elseif ($count > 1) {
    // count is more than 1, give us a random image
    shuffle($tids);
  }
  return $tids[0];
}
?>

Notes:
php random sort array
http://us.php.net/shuffle

this arg code could be extended to do something different if arg(0) does NOT equal 'node' (right now it does nothing)

Resolution

Searched words: 
"Views 2" filter by node taxonomy term Drupal Views 2 node taxonomy term relate node auto term to taxonomy view display related views

Comments

Yup, harder to find where to do it now

Thanks for another great tip, Benjamin!

I have used the method described above both in d5 and d6, it's true the first time in d6 it took me a while to find where to put my php code for argument handling, but it is there :)

I was kind of hoping views2 would include this in the UI. The first time i saw views2 I thought great! we can have relationships... but it looks like (correct me if I am wrong) that relationships do not work with the arguments you provide the view with. This I was hoping for, but unless I am mistaken, it is not the case.

So let's say you pull the node ID from the URL as the argument, wouldn't it be nice if the relationship could pull data from that node, and provide the fields for the view to display? Right... I'll keep dreaming ;)

check this out for a good

You should not use $node =

You should not use $node = node_load(arg(1)); for getting a node object. If it's a node page, then $node is already loaded. You should just insert global $node; and use global $node.

And a less restrictive capcha would be great...

node_load uses static caching

node_load() uses static caching (it produces no database calls when used for the present node page) so I wouldn't fear using it anywhere it can make the code more portable and less likely to break in hard to debug ways.

I see your point though and hell yeah about the CAPTCHA.

Post new comment

The content of this field is kept private and will not be shown publicly.
  • You may post code using <code>...</code> (generic) or <?php ... ?> (highlighted PHP) tags.
  • You can use Markdown syntax to format and style the text. Also see Markdown Extra for tables, footnotes, and more.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd> <img> <blockquote> <small> <h2> <h3> <h4> <h5> <h6> <sub> <sup> <p> <br> <strike> <table> <tr> <td> <thead> <th> <tbody> <tt> <output>
  • Lines and paragraphs break automatically.

More information about formatting options

By submitting this form, you accept the Mollom privacy policy.