1

I'm attempting to add a coupon to an order when an item is added to the cart. I've added an event subscriber for commerce_cart.entity.add. Within the subscriber, I use $to_apply->getPromotion()->apply($event->getCart());.

This does end up in Promotion::apply() and does call $offer->apply(), but the coupon doesn't seem to actually get applied. I've tried to see if, once we arrive at /checkout/{order_id}, the promotions/coupons are reset. AFAICT, they are not.

I have confirmed that I can manually apply the coupon once on /checkout/{order_id}.

What am I missing?

1 Answer 1

1

Got an answer via Slack. You only need to update the OrderInteface and set the coupons property, then resave the order. PromotionOrderProcessor handles applying the coupon to the order.

Something like this should work within your event subscriber:

  /** @var \Drupal\commerce_promotion\Entity\Coupon $to_apply */
  $to_apply = $coupon
  /** @var OrderInterface $cart */
  $cart = $event->getCart();
  $cart->set('coupons', $to_apply);
  $cart->save();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.