Prestashop 14 : Limiter la quantité des produits téléchargeables à 1 dans le panier

Ce tutoriel est compatible avec les versions de Prestashop suivantes :
1.4 1.7.8 +
Cet article est assez ancien, malgré toute l'attention que j' apporte à mes contenus il est possible que celui-ci ne soit plus d'actualité.
N'hésitez pas à me le signaler si nécessaire via le formulaire de contact.

Petite astuce rapide pour Prestashop 1.4.
Si vous vendez des produits téléchargeables qui n’ont aucun intérêt  à être ajouté au panier plus d’une fois, voici comment limiter cela rapidement.

Dans le fichier override/classes/Cart.php saisissez le code suivant :

Les codes ajoutés sont lignes 42,43 et 53-55

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
<?php
 
/**
 * Surcharge de la classe Panier
 */
class Cart extends CartCore
{
 
     /**
     * Update product quantity
     *
     * Ajout d'une limitation qui ne permet d'ajouter qu'une seule fois un produit téléchargeable au panier
     * 
     * @param integer $quantity Quantity to add (or substract)
     * @param integer $id_product Product ID
     * @param integer $id_product_attribute Attribute ID if needed
     * @param string $operator Indicate if quantity must be increased or decreased
     */
    public function updateQty($quantity, $id_product, $id_product_attribute = NULL, $id_customization = false, $operator = 'up')
    {
        $product = new Product((int)$id_product, false, (int)Configuration::get('PS_LANG_DEFAULT'));
 
        /* If we have a product combination, the minimal quantity is set with the one of this combination */
        if (!empty($id_product_attribute))
            $minimalQuantity = (int)Attribute::getAttributeMinimalQty((int)$id_product_attribute);
        else
            $minimalQuantity = (int)$product->minimal_quantity;
 
        if (!Validate::isLoadedObject($product))
            die(Tools::displayError());
        if (isset(self::$_nbProducts[$this->id]))
            unset(self::$_nbProducts[$this->id]);
        if (isset(self::$_totalWeight[$this->id]))
            unset(self::$_totalWeight[$this->id]);
        if ((int)$quantity <= 0)
            return $this->deleteProduct((int)$id_product, (int)$id_product_attribute, (int)$id_customization);
        else if (!$product->available_for_order OR Configuration::get('PS_CATALOG_MODE'))
            return false;
        else
        {
 
                    /* On determine si le produit est téléchargeable */
                    $isProductDownloadable = ProductDownloadCore::getIdFromIdProduct($product->id);
 
            /* Check if the product is already in the cart */
            $result = $this->containsProduct((int)$id_product, (int)$id_product_attribute, (int)$id_customization);
 
            /* Update quantity if product already exist */
            if ($result)
            {
                if ($operator == 'up')
                {
                                    /* Un produit téléchargeable ne peut être ajouté qu'une fois au panier */
                                    if ( $isProductDownloadable )
                                        return false;
 
                    $result2 = Db::getInstance()->getRow('
                        SELECT '.(!empty($id_product_attribute) ? 'pa' : 'p').'.`quantity`, p.`out_of_stock`
                        FROM `'._DB_PREFIX_.'product` p
                        '.(!empty($id_product_attribute) ? 'LEFT JOIN `'._DB_PREFIX_.'product_attribute` pa ON p.`id_product` = pa.`id_product`' : '').'
                        WHERE p.`id_product` = '.(int)($id_product).
                        (!empty($id_product_attribute) ? ' AND `id_product_attribute` = '.(int)$id_product_attribute : ''));
                    $productQty = (int)$result2['quantity'];
                    $newQty = (int)$result['quantity'] + (int)$quantity;
                    $qty = '+ '.(int)$quantity;
 
                    if (!Product::isAvailableWhenOutOfStock((int)$result2['out_of_stock']))
                        if ($newQty > $productQty)
                            return false;
                }
                elseif ($operator == 'down')
                {
                    $qty = '- '.(int)$quantity;
                    $newQty = (int)$result['quantity'] - (int)$quantity;
                    if ($newQty < $minimalQuantity AND $minimalQuantity > 1)
                        return -1;
                }
                else
                    return false;
 
                /* Delete product from cart */
                if ($newQty <= 0)
                    return $this->deleteProduct((int)$id_product, (int)$id_product_attribute, (int)$id_customization);
                else if ($newQty < $minimalQuantity)
                    return -1;
                else
                    Db::getInstance()->Execute('
                    UPDATE `'._DB_PREFIX_.'cart_product`
                    SET `quantity` = `quantity` '.$qty.', `date_add` = NOW()
                    WHERE `id_product` = '.(int)$id_product.
                    (!empty($id_product_attribute) ? ' AND `id_product_attribute` = '.(int)$id_product_attribute : '').'
                    AND `id_cart` = '.(int)$this->id.'
                    LIMIT 1');
            }
 
            /* Add product to the cart */
            else
            {
                $result2 = Db::getInstance()->getRow('
                SELECT '.(!empty($id_product_attribute) ? 'pa' : 'p').'.`quantity`, p.`out_of_stock`
                FROM `'._DB_PREFIX_.'product` p
                '.(!empty($id_product_attribute) ? 'LEFT JOIN `'._DB_PREFIX_.'product_attribute` pa ON p.`id_product` = pa.`id_product`' : '').'
                WHERE p.`id_product` = '.(int)$id_product.
                (!empty($id_product_attribute) ? ' AND `id_product_attribute` = '.(int)$id_product_attribute : ''));
 
                if (!Product::isAvailableWhenOutOfStock((int)$result2['out_of_stock']))
                    if ((int)$quantity > $result2['quantity'])
                        return false;
 
                if ((int)$quantity < $minimalQuantity)
                    return -1;
 
                if (!Db::getInstance()->AutoExecute(_DB_PREFIX_.'cart_product', array('id_product' => (int)$id_product,
                'id_product_attribute' => (int)$id_product_attribute, 'id_cart' => (int)$this->id,
                'quantity' => (int)$quantity, 'date_add' => date('Y-m-d H:i:s')), 'INSERT'))
                    return false;
            }
        }
        // refresh cache of self::_products
        $this->_products = $this->getProducts(true);
        $this->update(true);
 
        if ($product->customizable)
            return $this->_updateCustomizationQuantity((int)$quantity, (int)$id_customization, (int)$id_product, (int)$id_product_attribute, $operator);
        else
            return true;
    }
}

Vous obtiendrez ensuite le message d’erreur standard de Prestashop « vous avez atteint la quantité maximum pour ce produit » lorsque vous tentez de rajouter plus d’une fois un produit téléchargeable au panier

2 réflexions sur “Prestashop 14 : Limiter la quantité des produits téléchargeables à 1 dans le panier”

    1. Bonjour,
      Le code a pas mal évolué depuis, si je devrais reprendre ce fonctionnement à présent j’essaierais de faire un module qui utilise le hook actionBeforeCartUpdateQty ( situé dans le fichier classes\Cart.php ) ou a défaut de remettre le même fonctionnement dans cette classe.

      Cordialement,
      Hervé

Répondre à Tirips Annuler la réponse

Votre adresse e-mail ne sera pas publiée. Les champs obligatoires sont indiqués avec *