Score:-1

Set the quantity per product equal to value in input

us flag

I'm using the Commerce Ajax Add to Cart module to add a product to my cart using AJAX. I guess I'll have to do that by creating a patch.

It's working fine, but I'd like to change how a product is added to the cart. For example, users add 4 times the same product in the cart. I've already made some changes so the by default, the quantity in my item cart is four. For now, if users click on *Add to cart, then the quantity will be added to the cart.

Instead of adding the quantity to the cart, I'd like to update the quantity. If users click on Add to cart and the quantity is five, instead of adding five to the quantity, the quantity for the product is five instead of nine.

After digging, I've found on commerce/modules/cart/src/Form/AddToCartForm.php submitForm(), which uses the following code.

$this->entity = $this->cartManager->addOrderItem($cart, $order_item, $form_state->get(['settings', 'combine']));

I tried to remove the order item before adding the item (to "simulate" a quantity of 0) with this code.

$this->cartManager->removeOrderItem($cart, $order_item);

I also tried by updating the order item cart.

$this->entity = $this->cartManager->updateOrderItem($cart, $order_item, $form_state->get(['settings', 'combine']));

Neither of them gave the expected result.

Do you have any idea?

Score:-1
us flag

As I thought, I've ended up to create a patch for this feature.

Reminder, this not a hotfix, it's specific for my website.

diff --git a/modules/cart/src/CartManager.php b/modules/cart/src/CartManager.php
index 3b27ae77..b81db592 100644
--- a/modules/cart/src/CartManager.php
+++ b/modules/cart/src/CartManager.php
@@ -108,7 +108,8 @@ class CartManager implements CartManagerInterface {
       $matching_order_item = $this->orderItemMatcher->match($order_item, $cart->getItems());
     }
     if ($matching_order_item) {
-      $new_quantity = Calculator::add($matching_order_item->getQuantity(), $quantity);
+      //$new_quantity = Calculator::add($matching_order_item->getQuantity(), $quantity);
+      $new_quantity = $quantity; //TODO: voir si impact sur la partie menu ?
       $matching_order_item->setQuantity($new_quantity);
       $matching_order_item->save();
       $saved_order_item = $matching_order_item;
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.