From ef883c1f578d37b84300e06f6068457a6d100669 Mon Sep 17 00:00:00 2001
From: guy_schneerson <guy@blue-bag.com>
Date: Tue, 12 Jul 2011 12:16:16 +0100
Subject: [PATCH] fix cart validation for beta4

---
 commerce_stock.module |   23 ++++++++++++-----------
 1 files changed, 12 insertions(+), 11 deletions(-)

diff --git a/commerce_stock.module b/commerce_stock.module
index 80a67a6..3628efc 100644
--- a/commerce_stock.module
+++ b/commerce_stock.module
@@ -86,13 +86,15 @@ function commerce_stock_form_after_build($form, &$form_state) {
   }
 }
 
+
 /**
  * Implements hook_form_FORM_ID_alter().
  *
  * Alters the cart form to provide a validator for it.
  */
-function commerce_stock_form_commerce_line_item_views_form_commerce_cart_form_default_alter(&$form, &$form_state) {
-  $form['#validate'][] = 'commerce_stock_form_commerce_line_item_validate';
+
+function commerce_stock_form_views_form_commerce_cart_form_default_alter(&$form, &$form_state) {
+  $form['#validate'][] = 'commerce_stock_form_commerce_cart_validate';
 }
 
 /**
@@ -101,18 +103,17 @@ function commerce_stock_form_commerce_line_item_views_form_commerce_cart_form_de
  * Checks each line item to make sure that they have not requested more items
  * than we have in stock.
  */
-function commerce_stock_form_commerce_line_item_validate($form, &$form_state) {
-  foreach ($form['view']['#value']->result as $index => $row) {
-    // Check for quantity in $form_state.
-    $line_item = $row->_field_data['commerce_line_item_field_data_commerce_line_items_line_item_'];
-    $line_item_id = $line_item['entity']->line_item_id;
-    $product_id = $line_item['entity']->commerce_product['und'][0]['product_id'];
+function commerce_stock_form_commerce_cart_validate($form, &$form_state) {
+  $cnt = 0;
+  foreach ($form_state['line_items'] as $index => $line_item) {
+    $line_item_wrapper = entity_metadata_wrapper('commerce_line_item', $line_item);
+    $product_id = $line_item_wrapper->commerce_product->product_id->value();;
     $product = commerce_product_load($product_id);
-    $desired_purchase = $form_state['values']['edit_quantity'][$line_item_id];
-
+    $desired_purchase = $line_item_wrapper->quantity->value();  
     if ($remaining_stock = commerce_stock_product_check_out_of_stock($product_id, $desired_purchase)) {
-      form_set_error("edit_quantity][$line_item_id", t('Maximum stock of %title that can be purchased is %max', array('%title' => $product->title, '%max' => $remaining_stock)));
+      form_set_error("edit_quantity][$cnt", t('Maximum stock of %title that can be purchased is %max', array('%title' => $product->title, '%max' => $remaining_stock)));
     }
+    $cnt++;
   }
 }
 
-- 
1.7.3.1.msysgit.0

