Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Implements hook_field_formatter_view().
- */
- function custom_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) {
- $product_ids[] = $item['product_id'];
- }
- if ($display['type'] == 'custom_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)) {
- if ($cache = cache_get('products_nid_' . $entity->nid)) {
- $products = $cache->data;
- } else {
- // Sort products by attribute name if exists and sort alphabetically is actived.
- // Products types with attributes, are required. If the first product have attributes, all have them it.
- if ($settings['sort_alphabetically'] && isset(current($products)->field_product_accessory[LANGUAGE_NONE]['0']['tid'])) {
- $terms = array();
- foreach ($products as $product) {
- $terms[] = $product->field_product_accessory[LANGUAGE_NONE]['0']['tid'];
- }
- $terms = taxonomy_term_load_multiple(array_unique($terms));
- foreach ($terms as $key => $term) {
- $termsSort[$key] = $term->name;
- }
- asort($termsSort);
- $tmp_products = $products;
- unset($products);
- foreach ($termsSort as $key => $term) {
- foreach ($tmp_products as $product) {
- if ($product->field_product_accessory[LANGUAGE_NONE]['0']['tid'] == $key) {
- $products[] = $product;
- }
- }
- }
- cache_set('products_nid_' . $entity->nid, $products, 'cache');
- }
- }
- $type = !empty($settings['line_item_type']) ? $settings['line_item_type'] : 'product';
- $line_item = commerce_product_line_item_new(reset($products), $settings['default_quantity'], 0, array(), $type);
- $line_item->data['context']['product_ids'] = array_keys($products);
- $line_item->data['context']['add_to_cart_combine'] = $settings['combine'];
- $result[] = array(
- '#arguments' => array(
- 'form_id' => custom_commerce_cart_add_to_cart_form_id($product_ids),
- 'line_item' => $line_item,
- 'show_quantity' => $settings['show_quantity'],
- 'sort_alphabetically' => $settings['sort_alphabetically'],
- ),
- );
- }
- }
- return $result;
- }
Add Comment
Please, Sign In to add comment