首页 > 解决方案 > 如何为创建的每个新订单、产品等订阅 DrupalCommerce 2X 事件

问题描述

每当在 DrupalCommerce 2X 中创建新订单、产品时,我需要能够编写一个插件来获取订单、产品等。但我似乎无法弄清楚 Commerce 希望我如何做到这一点。我没有看到任何可以为我提供数据的 *events 文件。

看起来 Commerce 希望我创建一个单独的事件流插件来添加我想要的步骤,但我似乎找不到关于实现我自己的事件流的文档。

创建订单或产品时,您能否指导我找到运行代码的正确路径?我在正确的道路上吗?你能指出事件/事件订阅者流开发文档吗?

标签: phpdrupaldrupal-modulesdrupal-8drupal-commerce

解决方案


订单完成后,系统调用 commerce_order.place.post_transition。所以您需要在结帐完成时创建一个事件。

对过渡做出反应

示例 - 对订单“放置”转换做出反应。

// mymodule/src/EventSubscriber/MyModuleEventSubscriber.php
namespace Drupal\my_module\EventSubscriber;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Drupal\state_machine\Event\WorkflowTransitionEvent;

class MyModuleEventSubscriber implements EventSubscriberInterface {

  public static function getSubscribedEvents() {
    // The format for adding a state machine event to subscribe to is:
    // {group}.{transition key}.pre_transition or {group}.{transition key}.post_transition
    // depending on when you want to react.
    $events = ['commerce_order.place.post_transition' => 'onOrderPlace'];
    return $events;
  }

  public function onOrderPlace(WorkflowTransitionEvent $event) {
    // @todo Write code that will run when the subscribed event fires.
  }
}

告诉 Drupal 你的事件订阅者

您的事件订阅者应添加到模块基本目录中的 {module}.services.yml 中。

以下将在上一节中注册事件订阅者:

# mymodule.services.yml
services:
  my_module_event_subscriber:
    class: '\Drupal\my_module\EventSubscriber\MyModuleEventSubscriber'
    tags:
      - { name: 'event_subscriber' }

如需更多参考,请查看以下 URL: https ://docs.drupalcommerce.org/commerce2/developer-guide/orders/react-to-workflow-transitions#reacting-to-transitions


推荐阅读