You are here

function commerce_stock_form_commerce_cart_validate in Commerce Stock 7

Same name and namespace in other branches
  1. 7.2 commerce_stock.module \commerce_stock_form_commerce_cart_validate()

Form validator function for cart form.

Checks each line item to make sure that they have not requested more items than we have in stock.

1 string reference to 'commerce_stock_form_commerce_cart_validate'
commerce_stock_form_views_form_commerce_cart_form_default_alter in ./commerce_stock.module
Implements hook_form_FORM_ID_alter().

File

./commerce_stock.module, line 260
Allow commerce products to have stock levels associated with their SKU

Code

function commerce_stock_form_commerce_cart_validate($form, &$form_state) {

  // if user chose to remove an item then valid
  if ($form_state['triggering_element']['#value'] == t('Remove')) {
    return;
  }
  $line_item_index = array_keys($form_state['line_items']);
  foreach ($form_state['input']['edit_quantity'] as $index => $qty) {
    $line_item = $form_state['line_items'][$line_item_index[$index]];
    $line_item_wrapper = entity_metadata_wrapper('commerce_line_item', $line_item);
    if (in_array($line_item_wrapper
      ->getBundle(), commerce_product_line_item_types())) {
      $product_id = $line_item_wrapper->commerce_product->product_id
        ->value();
      $product = commerce_product_load($product_id);
      $product_wrapper = entity_metadata_wrapper('commerce_product', $product);
      if (!(isset($product_wrapper->commerce_stock_override) && $product_wrapper->commerce_stock_override
        ->value() == 1)) {
        if (commerce_stock_product_check_out_of_stock($product_id, $qty, $remaining_stock)) {
          form_set_error("edit_quantity][{$index}", t('The maximum stock of %title that can be purchased is %max.', array(
            '%title' => $product->title,
            '%max' => $remaining_stock,
          )));
        }
      }
    }
  }
}