You are here

function commerce_product_reference_field_formatter_prepare_view in Commerce Core 7

Implements hook_field_formatter_prepare_view().

File

modules/product_reference/commerce_product_reference.module, line 783
Defines a field type for referencing products from other entities.

Code

function commerce_product_reference_field_formatter_prepare_view($entity_type, $entities, $field, $instances, $langcode, &$items, $displays) {
  $display = reset($displays);
  if ($display['type'] == 'commerce_product_reference_rendered_product') {
    $product_ids = array();

    // Collect every possible entity attached to any of the entities.
    foreach ($entities as $id => $entity) {
      foreach ($items[$id] as $delta => $item) {
        if (isset($item['product_id'])) {
          $product_ids[] = $item['product_id'];
        }
      }
    }
    if ($product_ids) {
      $products = entity_load('commerce_product', $product_ids);
    }
    else {
      $products = array();
    }

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

        // Check whether the referenced product could be loaded and that the
        // user has access to it.
        if (isset($products[$item['product_id']]) && entity_access('view', 'commerce_product', $products[$item['product_id']])) {

          // Add the fully loaded entity to the items array.
          $items[$id][$delta]['entity'] = $products[$item['product_id']];
        }
        else {

          // Otherwise, unset the item since the referenced product does not
          // exist or is not be accessible to the user.
          unset($items[$id][$delta]);
          $rekey = TRUE;
        }
      }
      if ($rekey) {

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