事件提供:
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
services:
modulename.event_subscriber:
class: Drupal\modulename\EventSubscriber\CartEventSubscriber
arguments: ['@messenger', '@commerce_cart.cart_manager']
tags:
- { name: event_subscriber }
CartEventSubscriber.php
<?php
namespace Drupal\modulename\EventSubscriber;
use Drupal\commerce_cart\CartManagerInterface;
use Drupal\commerce_cart\Event\CartEntityAddEvent;
use Drupal\commerce_cart\Event\CartEvents;
use Drupal\commerce_product\Entity\ProductVariation;
use Drupal\Core\Messenger\MessengerInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
/**
* Cart Event Subscriber.
*/
class CartEventSubscriber implements EventSubscriberInterface {
/**
* The messenger.
*
* @var \Drupal\Core\Messenger\MessengerInterface
*/
protected $messenger;
/**
* The cart manager.
*
* @var \Drupal\commerce_cart\CartManagerInterface
*/
protected $cartManager;
/**
* Constructs event subscriber.
*
* @param \Drupal\Core\Messenger\MessengerInterface $messenger
* The messenger.
*/
public function __construct(MessengerInterface $messenger, CartManagerInterface $cart_manager) {
$this->messenger = $messenger;
$this->cartManager = $cart_manager;
}
/**
* {@inheritdoc}
*/
public static function getSubscribedEvents() {
return [
CartEvents::CART_ENTITY_ADD => [['addToCart', 100]]
];
}
/**
* Add a related product automatically
*
* @param \Drupal\commerce_cart\Event\CartEntityAddEvent $event
* The cart add event.
*
* @throws \Drupal\Core\TypedData\Exception\ReadOnlyException
*/
public function addToCart(CartEntityAddEvent $event) {
/** @var \Drupal\commerce_product\Entity\ProductVariationInterface $product_variation */
$product_variation = $event->getEntity();
if ($product_variation->getSku() === 'some_sku') {
$cart = $event->getCart();
// Load a known other product variation.
$variation = ProductVariation::load(5);
// Create a new order item based on the loaded variation.
$new_order_item = $this->cartManager->createOrderItem($variation);
$new_order_item->setQuantity(1);
// Add it to the cart.
$this->cartManager->addOrderItem($cart, $new_order_item);
}
}
}