You are here

function nodereference_field_formatter in Content Construction Kit (CCK) 5

Implementation of hook_field_formatter().

File

./nodereference.module, line 156
Defines a field type for referencing one node from another.

Code

function nodereference_field_formatter($field, $item, $formatter, $node) {
  static $titles = array();

  // We store the rendered nids in order to prevent infinite recursion
  // when using the 'full node' / 'teaser' formatters.
  static $recursion_queue = array();
  if (empty($item['nid']) || !is_numeric($item['nid'])) {
    return '';
  }
  if ($formatter == 'full' || $formatter == 'teaser') {

    // If no 'referencing node' is set, we are starting a new 'reference thread'
    if (!isset($node->referencing_node)) {
      $recursion_queue = array();
    }
    $recursion_queue[] = $node->nid;
    if (in_array($item['nid'], $recursion_queue)) {

      // Prevent infinite recursion caused by reference cycles :
      // if the node has already been rendered earlier in this 'thread',
      // we fall back to 'default' (node title) formatter.
      $formatter = 'default';
    }
    elseif ($referenced_node = node_load($item['nid'])) {
      $referenced_node->referencing_node = $node;
      $referenced_node->referencing_field = $field;
      $titles[$item['nid']] = $referenced_node->title;
    }
  }
  if (!isset($titles[$item['nid']])) {
    if ($title = db_result(db_query(db_rewrite_sql("SELECT title FROM {node} WHERE nid=%d"), $item['nid']))) {
      $titles[$item['nid']] = $title ? $title : '';
    }
  }
  if (empty($titles[$item['nid']])) {
    return '';
  }
  switch ($formatter) {
    case 'full':
      return $referenced_node ? node_view($referenced_node, FALSE) : '';
    case 'teaser':
      return $referenced_node ? node_view($referenced_node, TRUE) : '';
    case 'plain':
      return check_plain($titles[$item['nid']]);
    default:
      return $titles[$item['nid']] ? l($titles[$item['nid']], 'node/' . $item['nid']) : '';
  }
}