You are here

function text_noderef_field_formatter_view in Text or Nodereference 7

Implements hook_field_formatter_view().

File

./text_noderef.module, line 254
Text or nodereference field formatter for a text field and autocomplete widget.

Code

function text_noderef_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {

  // This function may be called several times on a single page, so cache
  // the already seen texts to a local static variable to speed up non-first
  // calls.
  $element = array();
  $settings = $display['settings'];
  if ($display['type'] == 'text_noderef_default') {
    $cache =& drupal_static(__FUNCTION__);
    $key = $instance['field_name'] . '@' . $instance['bundle'];
    foreach ($items as $delta => $item) {
      if (!isset($cache[$key]) || !isset($cache[$key][$item['value']])) {
        $query = new EntityFieldQuery();
        $query
          ->entityCondition('entity_type', 'node');
        $bundles = array_filter($instance['widget']['settings']['bundles']);
        if ($bundles) {
          $query
            ->entityCondition('bundle', $bundles, 'IN');
        }
        $query
          ->propertyCondition('status', 1)
          ->propertyCondition('title', $item['value'], 'LIKE')
          ->propertyOrderBy('title');
        $result = $query
          ->execute();
        if (isset($result['node'])) {
          reset($result['node']);
          $node = each($result['node']);
          $cache[$key][$item['value']] = l($item['value'], 'node/' . $node['value']->nid);
        }
        else {
          $cache[$key][$item['value']] = $item['safe_value'];
        }
      }
      $element[$delta] = array(
        '#markup' => $cache[$key][$item['value']],
      );
    }
  }
  return $element;
}