简体   繁体   中英

Magento 2 event observer not working

I'm trying to create a simple event observer for my Magento 2 page.

app/code/Ndac/Orderinfo/etc/event.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="sales_order_place_after">
       <observer name="OrderInfo" instance="Ndac\Orderinfo\Observer\OrderInfo" />
   </event>

</config>

app/code/Ndac/Orderinfo/etc/module.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
    <module name="Orderinfo" setup_version="1.0.0"></module>
</config>

app/code/Ndac/Orderinfo/registration.php

<?php \Magento\Framework\Component\ComponentRegistrar::register(\Magento\Framework\Component\ComponentRegistrar::MODULE,"Orderinfo", __DIR__);

app/code/Ndac/Orderinfo/Observer/OrderInfo.php

<?php
namespace Ndac\Orderinfo\Observer;

use Magento\Sales\Model\Order;
use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;

class OrderInfo implements ObserverInterface {
    // Tried it with constructor
    public __construct() {
        $file = fopen("/mnt/data/magento/test.txt", "w") or die ("die");
        fwrite($file, "test");
        fclose($file);
    }

    public function execute(Observer $observer)
    {
        $file = fopen("/mnt/data/magento/test.txt", "w") or die ("die")
        fwrite($file, "test");
        fclose($file);
    }
}
?>

I run the following command: bin/magento setup:upgrade and the module appears on the dashboard, and its enabled, but the test.txt remains empty, after I place an order.

There is an issue with the file naming.

app/code/Ndac/Orderinfo/etc/event.xml

this has to be as:

app/code/Ndac/Orderinfo/etc/events.xml

It has to be events.xml . And also if this event doesn't work, then try with the checkout_onepage_controller_success_action event.

Now run the upgrade command and clear the cache.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM