function commerce_stock_option_validate in Commerce Stock 7
Form validate handler: validate the product and quantity to add to the cart.
1 string reference to 'commerce_stock_option_validate'
- commerce_stock_form_alter in ./
commerce_stock.module - Implements hook_form_alter().
File
- ./
commerce_stock.module, line 285 - Allow commerce products to have stock levels associated with their SKU
Code
function commerce_stock_option_validate($element, &$form_state) {
// validate the stock level
// @todo we really dont need to cycle and load all the products
// only $form_state['values']['product_id']
$options = $element['#options'];
foreach ($options as $key => $value) {
$product = commerce_product_load($key);
$product_wrapper = entity_metadata_wrapper('commerce_product', $product);
if (isset($product_wrapper->commerce_stock)) {
// if stock override set stock to be the same as quantity so will validate
if (isset($product_wrapper->commerce_stock_override) && $product_wrapper->commerce_stock_override
->value() == 1) {
$element['#stock'][$key] = $form_state['values']['quantity'];
continue;
}
}
}
$stock = $element['#stock'][$form_state['values']['product_id']];
$stock_enabled = $element['#stock_enabled'][$form_state['values']['product_id']];
if ($stock < 1 && $stock_enabled) {
form_error($element, t('Product is out of stock'));
}
elseif ($stock_enabled) {
$product_id = $form_state['values']['product_id'];
$qty = $form_state['values']['quantity'];
$qty_ordered = commerce_stock_check_cart_product_level($product_id);
if ($qty + $qty_ordered > $stock) {
form_error($element, t("You can only order a maximum of @stock for this item.", array(
'@stock' => $stock,
)));
}
}
}