事件提供:

CartEvents::CART_EMPTY:清空购物车后触发。

CartEvents::CART_ENTITY_ADD:在将可购买实体添加到购物车后触发。

CartEvents::CART_ORDER_ITEM_UPDATE:在更新订单项目后激发。

CartEvents::CART_ORDER_ITEM_REMOVE:从购物车中删除订单项目后激发。

CartEvents::ORDER_ITEM_COMPARISON_FIELDS:在更改比较字段列表时触发-比较字段是Drupal commerce如何确定何时将商品添加到购物车中,该商品是否可以与现有商品组合。

实例:添加某个产品到购物车就会添加另外一个产品

我们在自定义模块中,定义一个事件订阅处理器:

modulename.services.yml

  1. services:
  2. modulename.event_subscriber:
  3. class: Drupal\modulename\EventSubscriber\CartEventSubscriber
  4. arguments: ['@messenger', '@commerce_cart.cart_manager']
  5. tags:
  6. - { name: event_subscriber }

CartEventSubscriber.php

  1. <?php
  2. namespace Drupal\modulename\EventSubscriber;
  3. use Drupal\commerce_cart\CartManagerInterface;
  4. use Drupal\commerce_cart\Event\CartEntityAddEvent;
  5. use Drupal\commerce_cart\Event\CartEvents;
  6. use Drupal\commerce_product\Entity\ProductVariation;
  7. use Drupal\Core\Messenger\MessengerInterface;
  8. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  9. /**
  10. * Cart Event Subscriber.
  11. */
  12. class CartEventSubscriber implements EventSubscriberInterface {
  13. /**
  14. * The messenger.
  15. *
  16. * @var \Drupal\Core\Messenger\MessengerInterface
  17. */
  18. protected $messenger;
  19. /**
  20. * The cart manager.
  21. *
  22. * @var \Drupal\commerce_cart\CartManagerInterface
  23. */
  24. protected $cartManager;
  25. /**
  26. * Constructs event subscriber.
  27. *
  28. * @param \Drupal\Core\Messenger\MessengerInterface $messenger
  29. * The messenger.
  30. */
  31. public function __construct(MessengerInterface $messenger, CartManagerInterface $cart_manager) {
  32. $this->messenger = $messenger;
  33. $this->cartManager = $cart_manager;
  34. }
  35. /**
  36. * {@inheritdoc}
  37. */
  38. public static function getSubscribedEvents() {
  39. return [
  40. CartEvents::CART_ENTITY_ADD => [['addToCart', 100]]
  41. ];
  42. }
  43. /**
  44. * Add a related product automatically
  45. *
  46. * @param \Drupal\commerce_cart\Event\CartEntityAddEvent $event
  47. * The cart add event.
  48. *
  49. * @throws \Drupal\Core\TypedData\Exception\ReadOnlyException
  50. */
  51. public function addToCart(CartEntityAddEvent $event) {
  52. /** @var \Drupal\commerce_product\Entity\ProductVariationInterface $product_variation */
  53. $product_variation = $event->getEntity();
  54. if ($product_variation->getSku() === 'some_sku') {
  55. $cart = $event->getCart();
  56. // Load a known other product variation.
  57. $variation = ProductVariation::load(5);
  58. // Create a new order item based on the loaded variation.
  59. $new_order_item = $this->cartManager->createOrderItem($variation);
  60. $new_order_item->setQuantity(1);
  61. // Add it to the cart.
  62. $this->cartManager->addOrderItem($cart, $new_order_item);
  63. }
  64. }
  65. }