You are here

function commerce_cart_field_formatter_view in Commerce Core 7

Implements hook_field_formatter_view().

File

modules/cart/commerce_cart.module, line 2732
Implements the shopping cart system and add to cart features.

Code

function commerce_cart_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  $settings = array_merge(field_info_formatter_settings($display['type']), $display['settings']);
  $result = array();

  // Collect the list of product IDs.
  $product_ids = array();
  foreach ($items as $delta => $item) {
    if (isset($item['product_id'])) {
      $product_ids[] = $item['product_id'];
    }
    elseif (module_exists('entityreference') && isset($item['target_id'])) {
      $product_ids[] = $item['target_id'];
    }
  }
  if ($display['type'] == 'commerce_cart_add_to_cart_form') {

    // Load the referenced products.
    $products = commerce_product_load_multiple($product_ids);

    // Check to ensure products are referenced, before returning results.
    if (!empty($products)) {
      $type = !empty($settings['line_item_type']) ? $settings['line_item_type'] : 'product';
      $line_item = commerce_product_line_item_new(commerce_product_reference_default_product($products), $settings['default_quantity'], 0, array(), $type);
      $line_item->data['context']['button_text'] = !empty($settings['button_text']) ? filter_xss($settings['button_text'], array()) : t('Add to cart');
      $line_item->data['context']['product_ids'] = array_keys($products);
      $line_item->data['context']['add_to_cart_combine'] = !empty($settings['combine']);
      $line_item->data['context']['show_single_product_attributes'] = !empty($settings['show_single_product_attributes']);
      $result[] = array(
        '#arguments' => array(
          'form_id' => commerce_cart_add_to_cart_form_id($product_ids),
          'line_item' => $line_item,
          'show_quantity' => $settings['show_quantity'],
        ),
      );
    }
  }
  return $result;
}