You are here

function recipe_field_formatter_prepare_view in Recipe 7.2

Implements hook_field_formatter_prepare_view().

File

./recipe.module, line 674
Contains functions for Recipe node CRUD and display.

Code

function recipe_field_formatter_prepare_view($entity_type, $entities, $field, $instances, $langcode, &$items, $displays) {

  // Attach recipe.css to style the ingredient field.
  drupal_add_css(drupal_get_path('module', 'recipe') . '/recipe.css');
  $iids = array();
  $ingredients = array();
  $unit_list = recipe_get_units();

  // Find every iid referenced by the entities.
  foreach ($entities as $id => $entity) {

    // Process recipe ingredient formatter views.
    if ($displays[$id]['type'] == 'recipe_ingredient_default') {
      foreach ($items[$id] as $delta => $item) {

        // Check for import preview mode which will have a name, but not an iid.
        if (!isset($item['name']) && isset($item['iid'])) {
          $iids[$item['iid']] = $item['iid'];
        }
      }
    }
  }

  // Load all of the ingredients found in the entities.
  foreach ($iids as $iid) {
    $ingredients[$iid] = recipe_load_ingredient($iid);
  }

  // Iterate through the entities again to attach the loaded ingredient data.
  foreach ($entities as $id => $entity) {
    $rekey = FALSE;

    // Process recipe ingredient formatter views.
    if ($displays[$id]['type'] == 'recipe_ingredient_default') {
      foreach ($items[$id] as $delta => $item) {

        // Check for import preview mode or if the ingredient could be loaded.
        if (isset($item['name'])) {

          // Add the ingredient data to the instance value.
          $items[$id][$delta]['link'] = '';

          // Add the unit data to the instance value.
          $items[$id][$delta]['unit'] = isset($unit_list[$item['unit_key']]) ? $unit_list[$item['unit_key']] : array();
        }
        elseif (isset($ingredients[$item['iid']])) {

          // Add the ingredient data to the instance value.
          $ingredient = $ingredients[$item['iid']];
          $items[$id][$delta]['name'] = $ingredient->name;
          $items[$id][$delta]['link'] = $ingredient->link;

          // Add the unit data to the instance value.
          $items[$id][$delta]['unit'] = isset($unit_list[$item['unit_key']]) ? $unit_list[$item['unit_key']] : array();
        }
        else {
          unset($items[$id][$delta]);
          $rekey = TRUE;
        }
      }
    }
    if ($rekey) {

      // Rekey the items array.
      $items[$id] = array_values($items[$id]);
    }
  }
}