Magento 2观察员事件未触发

时间:2016-06-29 10:45:40

标签: magento magento2 magento2.0.2

我已将此观察者添加到我的模块中,并将事件定义放在events.xml

# app/code/Vendor/ModuleName/etc/frontend/events.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
    <event name="checkout_submit_before">
        <observer name="vendor_modulename_order_save_before" instance="Vendor\ModuleName\Observer\OrderObserver" />
    </event>
</config>

我在观察员中添加了一些逻辑

# app/code/Vendor/Name/Observer/OrderObserver.php
namespace Vendor\ModuleName\Observer;

use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;

class OrderObserver implements ObserverInterface
{

    public function __construct()
    {
    }

    /**
     * @param Observer $observer
     * @return void
     */
    public function execute(\Magento\Framework\Event\Observer $observer)
    {
        $quote = $observer->getQuote();
        ...
        ...
        ...
    }
}

1 个答案:

答案 0 :(得分:2)

尝试将 events.xml 设置为 etc / events.xml

# app/code/Vendor/ModuleName/etc/events.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
    <event name="checkout_submit_before">
        <observer name="vendor_modulename_order_save_before" instance="Vendor\ModuleName\Observer\OrderObserver" />
    </event>
</config>

并且无需使用Magento \ Framework \ Event \ Observer

# app/code/Vendor/ModuleName/Observer/OrderObserver.php
namespace Vendor\ModuleName\Observer;
use Magento\Framework\Event\ObserverInterface;

class OrderObserver implements ObserverInterface
{
    /**
     * @param Observer $observer
     * @return void
     */
    public function execute(\Magento\Framework\Event\Observer $observer)
    {
        $quote = $observer->getQuote();
        ...
        ...
        ...
    }
}

确保清理缓存

bin/magento cache:clean

如果您仍有问题,请告诉我