ajaxopencartopencart2.xopencart-module

Prevent 'Add to cart' If quantity Exceeds than stock


I want to disable adding a product to cart beyond its stock limit through ajax in opencart 2.x,Now opencart only shows a message on header "Products marked with *** are not available in the desired quantity or not in stock!". But i want products not to be added to cart if more is ordered than what's in stock,now openacart's stuff is time consuming as well as not advance for buyer to make changes again and again,

I tried but not sure where should i make changes ,whether it start in catalog/controller/api/cart.php or in common.js or system/lirary/cart.php ,i try this code-

     if ((int)$qty && ((int)$qty > 0)) {
        if( ($this->session->data['cart'][$key])==(int)$product['stock']){

        }
        else{
            if (!isset($this->session->data['cart'][$key])) {
            $this->session->data['cart'][$key] = (int)$qty;
        } else {
            $this->session->data['cart'][$key] += (int)$qty;
        }
        }

    }

Solution

  • If I understand your question, you want to prevent the customer from adding more to their cart than is remaining in stock?

    EDIT I've updated the code after checking in OpenCart 2.0.2.0.

    OK So first in your controller/checkout/cart.php before the line

    if ($json)
    

    in the add() function.

    you need the following:

    $quantity_in_cart = 0;
    
    $products = $this->cart->getProducts();
    foreach ($products as $product) {
        if ($product['product_id'] == $product_id) {
            $quantity_in_cart = $product['quantity'];
            break;
        }
    }
    
    if (($quantity + (int)$quantity_in_cart) > $product_info['quantity']) {
        $json['error']['stock'] = $this->language->get('error_not_enough_stock');
    }
    

    Then in product.tpl you need code added to the Javascript to display the error if the add fails. It should be placed in the function

    $('#button-cart').on('click', function() {
    

    after the lines...

    if (json['error']['recurring']) {
        $('select[name=\'recurring_id\']').after('<div class="text-danger">' + json['error']['recurring'] + '</div>');
    }
    

    The added code is...

    if (json['error']['stock']) {
        $('.breadcrumb').after('<div class="alert alert-danger">' + json['error']['stock'] + '<button type="button" class="close" data-dismiss="alert">&times;</button></div>');
    }
    

    Of course you'll have to add similar code to any other tpl that adds products to the cart, and things get more complex when you've got products with options, but this is the basics of it.