You are here

nodereference.module in Content Construction Kit (CCK) 6

Defines a field type for referencing one node from another.

File

modules/nodereference/nodereference.module
View source
<?php

/**
 * @file
 * Defines a field type for referencing one node from another.
 */

/**
 * Implementation of hook_menu().
 */
function nodereference_menu() {
  $items = array();
  $items['nodereference/autocomplete'] = array(
    'title' => 'Nodereference autocomplete',
    'page callback' => 'nodereference_autocomplete',
    'access arguments' => array(
      'access content',
    ),
    'type' => MENU_CALLBACK,
  );
  return $items;
}

/**
 * Implementation of hook_theme().
 */
function nodereference_theme() {
  return array(
    'nodereference_item_simple' => array(
      'arguments' => array(
        'item' => NULL,
      ),
    ),
    'nodereference_item_advanced' => array(
      'arguments' => array(
        'item' => NULL,
        'view' => NULL,
      ),
    ),
    'nodereference_select' => array(
      'arguments' => array(
        'element' => NULL,
      ),
    ),
    'nodereference_autocomplete' => array(
      'arguments' => array(
        'element' => NULL,
      ),
    ),
    'nodereference_formatter_default' => array(
      'arguments' => array(
        'element',
      ),
    ),
    'nodereference_formatter_full' => array(
      'arguments' => array(
        'element',
      ),
      'function' => 'theme_nodereference_formatter_full_teaser',
    ),
    'nodereference_formatter_teaser' => array(
      'arguments' => array(
        'element',
      ),
      'function' => 'theme_nodereference_formatter_full_teaser',
    ),
  );
}

/**
 * Implementation of hook_field_info().
 *
 * Here we indicate that the content module will use its default
 * handling for the view of this field.
 *
 * Callbacks can be omitted if default handing is used.
 * They're included here just so this module can be used
 * as an example for custom modules that might do things
 * differently.
 */
function nodereference_field_info() {
  return array(
    'nodereference' => array(
      'label' => t('Node reference'),
      'description' => t('Store the ID of a related node as an integer value.'),
      'callbacks' => array(
        'tables' => CONTENT_CALLBACK_DEFAULT,
        'arguments' => CONTENT_CALLBACK_DEFAULT,
      ),
    ),
  );
}

/**
 * Implementation of hook_field_settings().
 */
function nodereference_field_settings($op, $field) {
  switch ($op) {
    case 'form':
      $form = array();
      $form['referenceable_types'] = array(
        '#type' => 'checkboxes',
        '#title' => t('Content types that can be referenced'),
        '#multiple' => TRUE,
        '#default_value' => is_array($field['referenceable_types']) ? $field['referenceable_types'] : array(),
        '#options' => node_get_types('names'),
      );
      if (module_exists('views')) {
        $views = array(
          '--' => '--',
        );
        $all_views = views_get_all_views();
        foreach ($all_views as $view) {
          $views[t('Existing Views')][$view->name] = $view->name;
        }
        if (count($views) > 1) {
          $form['advanced'] = array(
            '#type' => 'fieldset',
            '#title' => t('Advanced - Nodes that can be referenced (View)'),
            '#collapsible' => TRUE,
            '#collapsed' => !isset($field['advanced_view']) || $field['advanced_view'] == '--',
          );
          $form['advanced']['advanced_view'] = array(
            '#type' => 'select',
            '#title' => t('View'),
            '#options' => $views,
            '#default_value' => isset($field['advanced_view']) ? $field['advanced_view'] : '--',
            '#description' => t('Choose the "Views module" view that selects the nodes that can be referenced.<br>Note :<ul><li>This will discard the "Content types" settings above. Use the view\'s "filters" section instead.</li><li>Use the view\'s "fields" section to display additional informations about candidate nodes on node creation/edition form.</li><li>Use the view\'s "sort criteria" section to determine the order in which candidate nodes will be displayed.</li></ul>'),
          );
          $form['advanced']['advanced_view_args'] = array(
            '#type' => 'textfield',
            '#title' => t('View arguments'),
            '#default_value' => isset($field['advanced_view_args']) ? $field['advanced_view_args'] : '',
            '#required' => FALSE,
            '#description' => t('Provide a comma separated list of arguments to pass to the view.'),
          );
        }
      }
      return $form;
    case 'save':
      $settings = array(
        'referenceable_types',
      );
      if (module_exists('views')) {
        $settings[] = 'advanced_view';
        $settings[] = 'advanced_view_args';
      }
      return $settings;
    case 'database columns':
      $columns = array(
        'nid' => array(
          'type' => 'int',
          'unsigned' => TRUE,
          'not null' => FALSE,
        ),
      );
      return $columns;
    case 'views data':
      $data = content_views_field_views_data($field);
      $db_info = content_database_info($field);
      $table_alias = content_views_tablename($field);

      // Swap the filter handler to the 'in' operator.
      $data[$table_alias][$field['field_name'] . '_nid']['filter']['handler'] = 'views_handler_filter_many_to_one_content';

      // Add a relationship for related node.
      $data[$table_alias][$field['field_name'] . '_nid']['relationship'] = array(
        'base' => 'node',
        'field' => $db_info['columns']['nid']['column'],
        'handler' => 'views_handler_relationship',
      );
      return $data;
  }
}

/**
 * Implementation of hook_field().
 */
function nodereference_field($op, &$node, $field, &$items, $teaser, $page) {
  switch ($op) {
    case 'validate':
      $refs = _nodereference_potential_references($field, TRUE);
      foreach ($items as $delta => $item) {
        if (is_array($item) && !empty($item['error_field'])) {
          $error_field = $item['error_field'];
          unset($item['error_field']);
          if (!empty($item['nid'])) {
            if (!in_array($item['nid'], array_keys($refs))) {
              form_set_error($error_field, t('%name : This post can\'t be referenced.', array(
                '%name' => t($field['widget']['label']),
              )));
            }
          }
        }
      }
      return $items;
  }
}

/**
 * Implementation of hook_content_is_empty().
 */
function nodereference_content_is_empty($item, $field) {
  if (empty($item['nid'])) {
    return TRUE;
  }
  return FALSE;
}

/**
 * Implementation of hook_field_formatter_info().
 */
function nodereference_field_formatter_info() {
  return array(
    'default' => array(
      'label' => t('Title (link)'),
      'field types' => array(
        'nodereference',
      ),
      'multiple values' => CONTENT_HANDLE_CORE,
    ),
    'plain' => array(
      'label' => t('Title (no link)'),
      'field types' => array(
        'nodereference',
      ),
      'multiple values' => CONTENT_HANDLE_CORE,
    ),
    'full' => array(
      'label' => t('Full node'),
      'field types' => array(
        'nodereference',
      ),
      'multiple values' => CONTENT_HANDLE_CORE,
    ),
    'teaser' => array(
      'label' => t('Teaser'),
      'field types' => array(
        'nodereference',
      ),
      'multiple values' => CONTENT_HANDLE_CORE,
    ),
  );
}

/**
 * Theme function for 'default' nodereference field formatter.
 */
function theme_nodereference_formatter_default($element) {
  $output = '';
  if (!empty($element['#item']['nid']) && is_numeric($element['#item']['nid']) && ($title = _nodereference_titles($element['#item']['nid']))) {
    $output = l($title, 'node/' . $element['#item']['nid']);
  }
  return $output;
}

/**
 * Theme function for 'plain' nodereference field formatter.
 */
function theme_nodereference_formatter_plain($element) {
  $output = '';
  if (!empty($element['#item']['nid']) && is_numeric($element['#item']['nid']) && ($title = _nodereference_titles($element['#item']['nid']))) {
    $output = check_plain($title);
  }
  return $output;
}

/**
 * Proxy theme function for 'full' and 'teaser' nodereference field formatters.
 */
function theme_nodereference_formatter_full_teaser($element) {
  static $recursion_queue = array();
  $output = '';
  if (!empty($element['#item']['nid']) && is_numeric($element['#item']['nid'])) {

    // 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($element['#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.
      return theme('nodereference_formatter_default', $element);
    }
    if ($referenced_node = node_load($element['#item']['nid'])) {
      $referenced_node->referencing_node = $node;
      $referenced_node->referencing_field = $field;
      _nodereference_titles($element['#item']['nid'], $referenced_node->title);
      $output = node_view($referenced_node, $element['#formatter'] == 'teaser');
    }
  }
  return $output;
}

/**
 * Helper function for formatters.
 *
 * Store node titles collected in the curent request.
 */
function _nodereference_titles($nid, $known_title = NULL) {
  static $titles = array();
  if (!isset($titles[$nid])) {
    $title = $known_title ? $known_title : db_result(db_query("SELECT title FROM {node} WHERE nid=%d", $nid));
    $titles[$nid] = $title ? $title : '';
  }
  return $titles[$nid];
}

/**
 * Implementation of hook_widget_info().
 *
 * We need custom handling of multiple values for the nodereference_select
 * widget because we need to combine them into a options list rather
 * than display multiple elements.
 *
 * We will use the content module's default handling for default value.
 *
 * Callbacks can be omitted if default handing is used.
 * They're included here just so this module can be used
 * as an example for custom modules that might do things
 * differently.
 */
function nodereference_widget_info() {
  return array(
    'nodereference_select' => array(
      'label' => t('Select list'),
      'field types' => array(
        'nodereference',
      ),
      'multiple values' => CONTENT_HANDLE_MODULE,
      'callbacks' => array(
        'default value' => CONTENT_CALLBACK_DEFAULT,
      ),
    ),
    'nodereference_autocomplete' => array(
      'label' => t('Autocomplete text field'),
      'field types' => array(
        'nodereference',
      ),
      'multiple values' => CONTENT_HANDLE_CORE,
      'callbacks' => array(
        'default value' => CONTENT_CALLBACK_DEFAULT,
      ),
    ),
  );
}

/**
 * Implementation of FAPI hook_elements().
 *
 * Any FAPI callbacks needed for individual widgets can be declared here,
 * and the element will be passed to those callbacks for processing.
 *
 * Drupal will automatically theme the element using a theme with
 * the same name as the hook_elements key.
 *
 * Autocomplete_path is not used by text_widget but other widgets can use it
 * (see nodereference and userreference).
 */
function nodereference_elements() {
  return array(
    'nodereference_select' => array(
      '#input' => TRUE,
      '#columns' => array(
        'uid',
      ),
      '#delta' => 0,
      '#process' => array(
        'nodereference_select_process',
      ),
    ),
    'nodereference_autocomplete' => array(
      '#input' => TRUE,
      '#columns' => array(
        'name',
      ),
      '#delta' => 0,
      '#process' => array(
        'nodereference_autocomplete_process',
      ),
      '#autocomplete_path' => FALSE,
    ),
  );
}

/**
 * Implementation of hook_widget().
 *
 * Attach a single form element to the form. It will be built out and
 * validated in the callback(s) listed in hook_elements. We build it
 * out in the callbacks rather than here in hook_widget so it can be
 * plugged into any module that can provide it with valid
 * $field information.
 *
 * Content module will set the weight, field name and delta values
 * for each form element. This is a change from earlier CCK versions
 * where the widget managed its own multiple values.
 *
 * If there are multiple values for this field, the content module will
 * call this function as many times as needed.
 *
 * @param $form
 *   the entire form array, $form['#node'] holds node information
 * @param $form_state
 *   the form_state, $form_state['values'][$field['field_name']]
 *   holds the field's form values.
 * @param $field
 *   the field array
 * @param $items
 *   array of default values for this field
 * @param $delta
 *   the order of this item in the array of subelements (0, 1, 2, etc)
 *
 * @return
 *   the form item for a single element for this field
 */
function nodereference_widget(&$form, &$form_state, $field, $items, $delta = 0) {
  switch ($field['widget']['type']) {
    case 'nodereference_select':
      $element = array(
        '#type' => 'nodereference_select',
        '#default_value' => $items,
      );
      break;
    case 'nodereference_autocomplete':
      $element = array(
        '#type' => 'nodereference_autocomplete',
        '#default_value' => isset($items[$delta]) ? $items[$delta] : NULL,
        '#value_callback' => 'nodereference_autocomplete_value',
      );
      break;
  }
  return $element;
}

/**
 * Value for a nodereference autocomplete element.
 *
 * Substitute in the node title for the node nid.
 */
function nodereference_autocomplete_value($element, $edit = FALSE) {
  $field_key = $element['#columns'][0];
  if (!empty($element['#default_value'][$field_key])) {
    $nid = $element['#default_value'][$field_key];
    $value = db_result(db_query(db_rewrite_sql('SELECT n.title FROM {node} n WHERE n.nid = %d'), $nid));
    $value .= ' [nid:' . $nid . ']';
    return array(
      $field_key => $value,
    );
  }
  return array(
    $field_key => NULL,
  );
}

/**
 * Process an individual element.
 *
 * Build the form element. When creating a form using FAPI #process,
 * note that $element['#value'] is already set.
 *
 * The $fields array is in $form['#field_info'][$element['#field_name']].
 */
function nodereference_select_process($element, $edit, $form_state, $form) {

  // The nodereference_select widget doesn't need to create its own
  // element, it can wrap around the optionwidgets_select element.
  // Add a validation step where the value can be unwrapped.
  $field_key = $element['#columns'][0];
  $element[$field_key] = array(
    '#type' => 'optionwidgets_select',
    '#default_value' => isset($element['#value']) ? $element['#value'] : '',
    '#element_validate' => array(
      'optionwidgets_validate',
      'nodereference_select_validate',
    ),
    // The following values were set by the content module and need
    // to be passed down to the nested element.
    '#field_name' => $element['#field_name'],
    '#delta' => $element['#delta'],
    '#columns' => $element['#columns'],
    '#title' => $element['#title'],
    '#required' => $element['#required'],
    '#description' => $element['#description'],
  );
  return $element;
}

/**
 * Process an individual element.
 *
 * Build the form element. When creating a form using FAPI #process,
 * note that $element['#value'] is already set.
 *
 */
function nodereference_autocomplete_process($element, $edit, $form_state, $form) {

  // The nodereference autocomplete widget doesn't need to create its own
  // element, it can wrap around the text_textfield element and add an autocomplete
  // path and some extra processing to it.
  // Add a validation step where the value can be unwrapped.
  $field_key = $element['#columns'][0];
  $element[$field_key] = array(
    '#type' => 'text_textfield',
    '#default_value' => isset($element['#value']) ? $element['#value'] : '',
    '#autocomplete_path' => 'nodereference/autocomplete/' . $element['#field_name'],
    '#element_validate' => array(
      'nodereference_autocomplete_validate',
    ),
    // The following values were set by the content module and need
    // to be passed down to the nested element.
    '#field_name' => $element['#field_name'],
    '#delta' => $element['#delta'],
    '#columns' => $element['#columns'],
    '#title' => $element['#title'],
    '#required' => $element['#required'],
    '#description' => $element['#description'],
  );
  return $element;
}

/**
 * Validate an select element.
 *
 * Remove the wrapper layer and set the right element's value.
 */
function nodereference_select_validate($element, &$form_state) {
  $field_key = $element['#columns'][0];
  array_pop($element['#parents']);
  form_set_value($element, $form_state['values'][$element['#field_name']][$field_key], $form_state);
}

/**
 * Validate an autocomplete element.
 *
 * Remove the wrapper layer and set the right element's value.
 */
function nodereference_autocomplete_validate($element, &$form_state) {
  $field_name = $element['#field_name'];
  $field = content_fields($field_name);
  $field_key = $element['#columns'][0];
  $delta = $element['#delta'];
  $value = $element['#value'][$field_key];
  $nid = NULL;
  if (!empty($value)) {
    preg_match('/^(?:\\s*|(.*) )?\\[\\s*nid\\s*:\\s*(\\d+)\\s*\\]$/', $value, $matches);
    if (!empty($matches)) {

      // explicit nid
      list(, $title, $nid) = $matches;
      if (!empty($title) && ($n = node_load($nid)) && $title != $n->title) {
        form_set_error($element[$field_key], t('%name: Title mismatch. Please check your selection.'), array(
          '%name' => t($element[$field_key]['#title']),
        ));
      }
    }
    else {

      // no explicit nid
      // TODO :
      // the best thing would be to present the user with an additional form,
      // allowing the user to choose between valid candidates with the same title
      // ATM, we pick the first matching candidate...
      $nids = _nodereference_potential_references($field, FALSE, $value, TRUE);
      $nid = !empty($nids) ? array_shift(array_keys($nids)) : 0;
    }
  }
  form_set_value($element, $nid, $form_state);
  return $element;
}

/**
 * Implementation of hook_allowed_values().
 */
function nodereference_allowed_values($field) {
  $options = _nodereference_potential_references($field, TRUE);
  foreach ($options as $key => $value) {
    $options[$key] = _nodereference_item($field, $value);
  }
  if (!$field['required']) {
    $options = array(
      0 => '<' . t('none') . '>',
    ) + $options;
  }
  return $options;
}

/**
 * Fetch an array of all candidate referenced nodes,
 * for use in presenting the selection form to the user.
 */
function _nodereference_potential_references($field, $return_full_nodes = FALSE, $string = '', $exact_string = false) {
  if (module_exists('views') && isset($field['advanced_view']) && $field['advanced_view'] != '--' && ($view = views_get_view($field['advanced_view']))) {

    // advanced field : referenceable nodes defined by a view
    // let views.module build the query
    $view
      ->init();

    // TODO is this the right way to do this?
    // make sure the fields get included in the query.
    // TODO Which display should we use here?
    // In our Views 1 to Views 2 updates we are
    // putting fields in the 'default' display.
    $display = 'default';
    $view
      ->set_display($display);
    $view->display[$display]->style_plugin = 'list';

    // Add arguments for the view.
    if (isset($field['advanced_view_args'])) {

      // TODO: Support Tokens using token.module ?
      $view_args = array();
      $view_args = array_map('trim', explode(',', $field['advanced_view_args']));
      $view
        ->set_arguments($view_args);
    }
    if (isset($string)) {

      //We do need title field, so add it if not present (unlikely, but...)
      if (!array_key_exists('title', $view->display[$display]->display_options['fields'])) {
        $view
          ->add_item($display, 'field', 'node', 'title');
      }

      // We use the title filter in the view, so make sure it's there.
      if (!array_key_exists('title', $view->display[$display]->display_options['filters'])) {
        $view
          ->add_item($display, 'filter', 'node', 'title');
      }

      // TODO Is this the best way to set values?
      $view->display[$display]->display_options['filters']['title']['value'] = $string;
      $view->display[$display]->display_options['filters']['title']['operator'] = $exact_string ? '=' : 'contains';
    }

    // Make sure the query is not cached
    $view->is_cacheable = FALSE;
    $view
      ->render();
    $options = array();
    foreach ($view->result as $row) {
      foreach ($view->field as $field) {
        if (!empty($field['handler']) && is_object($field['handler'])) {
          $options[$row->nid][] = theme('views_view_field', $view, $field, $row);
        }
      }
    }
    return $options;
  }
  else {

    // standard field : referenceable nodes defined by content types
    // build the appropriate query
    $related_types = array();
    $args = array();
    if (is_array($field['referenceable_types'])) {
      foreach ($field['referenceable_types'] as $related_type) {
        if ($related_type) {
          $related_types[] = " n.type = '%s'";
          $args[] = $related_type;
        }
      }
    }
    $related_clause = implode(' OR ', $related_types);
    if (!count($related_types)) {
      return array();
    }
    if (isset($string)) {
      $string_clause = $exact_string ? " AND n.title = '%s'" : " AND n.title LIKE '%%%s%'";
      $related_clause = "(" . $related_clause . ")" . $string_clause;
      $args[] = $string;
    }
    $result = db_query(db_rewrite_sql("SELECT n.nid, n.title AS node_title, n.type AS node_type FROM {node} n WHERE " . $related_clause . " ORDER BY n.title, n.type"), $args);
  }
  $rows = array();
  while ($node = db_fetch_object($result)) {
    if ($return_full_nodes) {
      $rows[$node->nid] = $node;
    }
    else {
      $rows[$node->nid] = $node->node_title;
    }
  }
  return $rows;
}

/**
 * Retrieve a pipe delimited string of autocomplete suggestions
 */
function nodereference_autocomplete($field_name, $string = '') {
  $fields = content_fields();
  $field = $fields[$field_name];
  $matches = array();
  foreach (_nodereference_potential_references($field, TRUE, $string) as $row) {
    $matches[$row->node_title . ' [nid:' . $row->nid . ']'] = _nodereference_item($field, $row, TRUE);
  }
  drupal_json($matches);
}
function _nodereference_item($field, $item, $html = FALSE) {
  if (module_exists('views') && isset($field['advanced_view']) && $field['advanced_view'] != '--' && ($view = views_get_view($field['advanced_view']))) {
    $field_names = array();
    $view
      ->render();
    foreach ($view->field as $name => $viewfield) {
      $field_names[] = isset($viewfield->definition['content_field_name']) ? $viewfield->definition['content_field_name'] : $name;
    }
    $output = theme('nodereference_item_advanced', $item, $field_names, $view);
    if (!$html) {

      // Views theming runs check_plain (htmlentities) on the values.
      // We reverse that with html_entity_decode.
      $output = html_entity_decode(strip_tags($output), ENT_QUOTES);
    }
  }
  else {
    $output = theme('nodereference_item_simple', $item);
    $output = $html ? check_plain($output) : $output;
  }
  return $output;
}
function theme_nodereference_item_advanced($item, $field_names, $view) {
  $item_fields = array();
  foreach ($item as $delta => $value) {

    // remove link tags (ex : for node titles)
    $value = preg_replace('/<a[^>]*>(.*)<\\/a>/iU', '$1', $value);
    if (!empty($value)) {
      $item_fields[] = "<span class='view-field view-data-{$field_names[$delta]}'>{$value}</span>";
    }
  }
  $output = implode(' - ', $item_fields);
  $output = "<span class='view-item view-item-{$view->name}'>{$output}</span>";
  return $output;
}
function theme_nodereference_item_simple($item) {
  return $item->node_title;
}

/**
 * FAPI theme for an individual elements.
 *
 * The textfield or select is already rendered by the
 * textfield or select themes and the html output
 * lives in $element['#children']. Override this theme to
 * make custom changes to the output.
 *
 * $element['#field_name'] contains the field name
 * $element['#delta]  is the position of this element in the group
 */
function theme_nodereference_select($element) {
  return $element['#children'];
}
function theme_nodereference_autocomplete($element) {
  return $element['#children'];
}

Functions

Namesort descending Description
nodereference_allowed_values Implementation of hook_allowed_values().
nodereference_autocomplete Retrieve a pipe delimited string of autocomplete suggestions
nodereference_autocomplete_process Process an individual element.
nodereference_autocomplete_validate Validate an autocomplete element.
nodereference_autocomplete_value Value for a nodereference autocomplete element.
nodereference_content_is_empty Implementation of hook_content_is_empty().
nodereference_elements Implementation of FAPI hook_elements().
nodereference_field Implementation of hook_field().
nodereference_field_formatter_info Implementation of hook_field_formatter_info().
nodereference_field_info Implementation of hook_field_info().
nodereference_field_settings Implementation of hook_field_settings().
nodereference_menu Implementation of hook_menu().
nodereference_select_process Process an individual element.
nodereference_select_validate Validate an select element.
nodereference_theme Implementation of hook_theme().
nodereference_widget Implementation of hook_widget().
nodereference_widget_info Implementation of hook_widget_info().
theme_nodereference_autocomplete
theme_nodereference_formatter_default Theme function for 'default' nodereference field formatter.
theme_nodereference_formatter_full_teaser Proxy theme function for 'full' and 'teaser' nodereference field formatters.
theme_nodereference_formatter_plain Theme function for 'plain' nodereference field formatter.
theme_nodereference_item_advanced
theme_nodereference_item_simple
theme_nodereference_select FAPI theme for an individual elements.
_nodereference_item
_nodereference_potential_references Fetch an array of all candidate referenced nodes, for use in presenting the selection form to the user.
_nodereference_titles Helper function for formatters.