views:

52

answers:

2

I have created a custom module and am using hook_block to programmatically create some blocks.

My question is how can I access field values including CCK fields for the current node within my module?

I basically want to get a value from a CCK field and use the value when building my block for that page.

+3  A: 

Getting at the current node is an awkward pain in the posterior. Standard practice is to do something like this:

if (arg(0) == 'node' && is_numeric(arg(1)) && arg(2) == '') {
  $node = node_load(arg(1));
  // Collect output.
}

arg() pulls elements out of the Drupal path. Since all nodes (regardless of what a path alias might show you) appears at node/#, by checking for 'node' and that the second element is a number, you are fairly well guaranteed to have your hands on a node. Checking the third path element allows you to avoid processing on the node edit form and other pages that hang off a specific node.

CCK Values are loaded into the node, and usually look something like this:

// Text field. Structure also works for number fields.
$text = $node->field_my_text_field[0]['value']
// Node Reference field.
$nref = $node->field_my_nref_field[0]['nid']
// User Reference field.
$uref = $node->field_my_uref_field[0]['uid']

The "0" array element specifies the delta of the field. Any given field can actually process multiple values, and the array structure in CCK assumes this possibility even if you restrict the field to a single value.

Grayside
That's fantastic thanks. I'm surprised there is not an built-in Drupal function to get the node id!
Camsoft
A: 

In Drupal 6 there is a built-in Drupal function to get the node object.

if ($node = menu_get_object()) {
  …
}

Read more here http://api.drupal.org/api/function/menu_get_item/6.

frjo