You are here

function computed_field_field_formatter_view in Computed Field 7

Implements hook_field_formatter_view().

File

./computed_field.module, line 392
Functionality for the computed field.

Code

function computed_field_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  $element = array();
  $data_to_display = FALSE;

  // Special case formatter that returns the raw computed values without any display code processing.
  if ($display['type'] == 'computed_field_computed_value') {
    foreach ($items as $delta => $item) {
      if (!isset($entity_field_item['value'])) {
        $entity_field_item['value'] = NULL;
      }
      $element[$delta] = array(
        '#markup' => $item['value'],
      );
    }
    return $element;
  }

  // Other display formatters which run through display code processing.
  // Check if the value is to be formatted by a display function outside the DB.
  $display_func = 'computed_field_' . $field['field_name'] . '_display';
  $display_in_code = function_exists($display_func);

  // Loop the items to display.
  foreach ($items as $delta => $item) {

    // For "some" backwards compatibility.
    $entity_field_item = $item;

    // Setup a variable with the entity language if available.
    if (isset($entity->language)) {
      $entity_lang = $entity->language;
    }
    else {
      $entity_lang = LANGUAGE_NONE;
    }

    // If there are value "holes" in the field array let's set the value to NULL,
    // to avoid undefined index errors in typical PHP display code.
    if (!isset($entity_field_item['value'])) {
      $entity_field_item['value'] = NULL;
    }

    // Execute the display code.
    $display_output = NULL;
    if ($display_in_code) {
      $display_output = $display_func($field, $entity_field_item, $entity_lang, $langcode, $entity);
    }
    else {
      eval($field['settings']['display_format']);
    }

    // Track if any of our items produce non-empty output.
    if (!empty($display_output) || is_numeric($display_output)) {
      $data_to_display = TRUE;
    }

    // Output the formatted display item.
    switch ($display['type']) {
      case 'computed_field_unsanitized':
        $element[$delta] = array(
          '#markup' => $display_output,
        );
        break;
      case 'computed_field_plain':
        $element[$delta] = array(
          '#markup' => check_plain($display_output),
        );
        break;
      case 'computed_field_markup':
        $element[$delta] = array(
          '#markup' => check_markup($display_output),
        );
        break;
    }
  }

  // If all items are empty then we should not return anything. This helps
  // ensure that empty fields are not displayed at all. This check does not
  // apply to fields stored in the DB as those are instead checked on save.
  if (isset($field['settings']['store']) && !$field['settings']['store'] && !$data_to_display) {
    return;
  }
  return $element;
}