Search code examples
phpmodel-view-controllermoduleprestashopprestashop-1.6

Prestashop add product to cart strange quantity


I am trying to add a product to PrestaShop cart programmatically. I use the updateQty() together with the quantity to update and the product id. However when I add the product to cart, it automatically adds 10 quantities of product. Am I using it the wrong way around?

I am using the actionCartSave hook in my custom module.

I have tried this:

public function hookActionCartSave($params){
    $cart = $params['cart'];
    $cart->updateQty(1, 408);
} 

Solution

  • The hookActionCartSave is called one more time at once. So every time that it will be called you increase of 1 the quantity in the cart of that product (in your case with id 408), maybe it is called 10 times in your case.

    To answer to your problem, we have to check if the product is already in the cart, try this snippet:

    public function hookActionCartSave($params)
    {
        $cart = $params['cart']; // Get the cart object
        if(Validate::isLoadedObject($cart)){ // Check if the cart is a valid object
            if(!$cart->containsProduct(408)){ // Check if our product is already in cart
                $cart->updateQty(1, 408); // Add our product to cart
            }
        }
    }
    

    Adapts the code to your needs ;)