Is it possible to set a block to only display on on nodes that have a certain value chosen from a CCK field?

I have a field named field_primarygenre and I wish to set a block to display only on pages which contain 'Electronica/Dance' in this field.

How can I set that?

Comments

marcvangend’s picture

Basically what I would do is:
- get the node ID
- load the node with node_load()
- find the key in the node object, check it's value and return true or false

In code, this would look something like this:

<?php
if ( arg(0) == 'node' && is_numeric(arg(1)) && ! arg(2) ) {
  $node = node_load(arg(1));
  if ($node->field_primarygenre[0]['value'] == "Electronica/Dance") {
    return TRUE;
  } else {
    return FALSE;
  }
}
?>

I'm not sure about the field_primarygenre[0]['value'] part, you may have to check this using print_r().
Hope this helps.

eviljoker7075’s picture

Help!? Help!? It was more than help, it was only the correct answer!!

Thank you very much :)

Just one small point, as I'm new to PHP maybe I just misunderstood your term, but when you said you get the node id, does that mean it will only work if the node with that value has the correct primarygenre field or what?

Also, I'm guessing I can change Electroica/Dance to any of my other listed genres...?

marcvangend’s picture

You're welcome, your post happened to cross my virtual path on one of my better moments :-)

When I say 'get the node ID', I mean that you get the ID (a number) of the node that is currently displayed. The path to a node looks like [yourdomain]/node/[nid] where [nid] is the node ID. In Drupal, arg() is the function which takes information from the current path. You can see that the php code first checks if the current path starts with 'node' (arg(0) == 'node') and if there is a number in the second position (is_numeric(arg(1))). If this is the case, the information from that node is retrieved from the database using node_load([nid]) and the returned object is called $node. Now we can use the information in $node and do whatever we want to do with it.

And yes, of course you can change the values in the code and check every key in the $node object.