Quantity gets multiplied when there is no quantity widget on the add-to-cart form

Created on 25 January 2024, 8 months ago
Updated 29 February 2024, 6 months ago

Problem/Motivation

When using attributes, and no quantity widget on the add-to-cart form, the quantity gets multiplied.

Commerce seems to grab the quantity in the order if an explicit quantity is not provided by the add-to-cart form.
This only happens from what I have seen with ajax, and when attributes are being used.

Steps to reproduce

Disable the quantity widget from the order item type, and make an attribute selection, and add to cart.
as you continue to add to cart you will see the quantity goes 1 - 2 - 4 - 8 - 16 - 32 - 64 - 128 etc.

Proposed resolution

I think this might be handled best in Commerce Core, but we might be able to check the order item display, and hardcode a quantity of 1 where the quantity widget is absent.

Something like this:

  /** @var \Drupal\commerce_order\Entity\OrderItemInterface $order_item */
  $order_item = $form_state->getFormObject()->getEntity();
  if ($order_item) {
    $order_item_display = EntityFormDisplay::collectRenderDisplay($order_item, 'add_to_cart');
    if (empty($order_item_display->getComponent('quantity'))) {
      $order_item->setQuantity(1);
    }
  }

The only thing I don't like about this is that I am not sure how many people might use custom quantity widgets. This fix would not cover them.

We could make the check more general for commerce_quantity fields, which seems to catch more use cases...

Here is a video from the original poster.
https://drive.google.com/file/d/1OpYMW12UWP3Md7RTVRKqeJ0PlxJSKHYd/view

🐛 Bug report
Status

Active

Version

1.0

Component

Code

Created by

🇮🇳India pritamdanve Mumbai

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Comments & Activities

Production build 0.71.5 2024