While working on #3138952: Make the AvailabilityManager order aware we noticed that order items being validated and passing to the availability manager from the AddToCartForm didn't have their cart attached. This is because we do not resolve and determine that cart until the form is submitted.

We need to figure out that cart in the buildEntity method so that it always has a reference.

This way folks can use the order item matcher in availability checks to see if the proposed quantity and the current quantity in the cart exceed expectations. (the fact someone has to do this manually can be a follow-up.)

Support from Acquia helps fund testing for Drupal Acquia logo

Comments

mglaman created an issue. See original summary.

jsacksick’s picture

Status: Active » Needs review
FileSize
1.55 KB

This should do the trick!

mglaman’s picture

+++ b/modules/cart/src/Form/AddToCartForm.php
@@ -204,10 +204,10 @@ class AddToCartForm extends ContentEntityForm implements AddToCartFormInterface
+    $cart = $order_item->getOrder();
     if (!$cart) {
+      $order_type_id = $this->orderTypeResolver->resolve($order_item);
+      $store = $this->selectStore($purchased_entity);
       $cart = $this->cartProvider->createCart($order_type_id, $store);
     }

I wonder if this is needed anymore. The entity should be built before submission.

  • \Drupal\Core\Entity\ContentEntityForm::validateForm builds the entity before it calls the validate method on the entity
  • \Drupal\Core\Entity\EntityForm::afterBuild rebuilds the entity if input is being processed
  • \Drupal\Core\Entity\EntityForm::submitForm also rebuilds the entity

The logic check protects us from additional calls, but maybe we can just remove that code.

mglaman’s picture

Since the submitForm parent calls build entity anyways, we're safe to assume the order has been set. Patch to verify.

Status: Needs review » Needs work

The last submitted patch, 4: addtocartform_should-3143382-3.patch, failed testing. View results

mglaman’s picture

Status: Needs work » Needs review
+++ b/modules/cart/src/Form/AddToCartForm.php
@@ -201,15 +201,8 @@ class AddToCartForm extends ContentEntityForm implements AddToCartFormInterface
-    $store = $this->selectStore($purchased_entity);
-    $cart = $this->cartProvider->getCart($order_type_id, $store);
-    if (!$cart) {
-      $cart = $this->cartProvider->createCart($order_type_id, $store);
-    }

🤦‍♂️ because this creates the cart, and I cannot read properly. We should definitely keep it here, otherwise we'd be creating carts on every product page view whenever building an order item entity for the add to cart form.

  • mglaman committed 012e218 on 8.x-2.x authored by jsacksick
    Issue #3143382 by mglaman, jsacksick: AddToCartForm should reference the...
mglaman’s picture

Status: Needs review » Fixed

Committed, good fix @jsacksick 🥳

Status: Fixed » Closed (fixed)

Automatically closed - issue fixed for 2 weeks with no activity.