Magento 2:sales_order_save_after

时间:2019-07-13 00:38:40

标签: php mysql magento2

触发事件sales_order_save_after后,不会插入新的数量值:

Autosynch \ Sale \ 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_save_after">
        <observer name="autosynch_sales_order_save_after" instance="Autosynch\Sale\Observer\OrderPlaceAfter" />
    </event>
</config>

Autosynch \ Sale \ 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="Autosynch_Sale" setup_version="0.0.1">
    </module>
</config>

Autosynch \ Sale \ registration.php

<?php /**
* Copyright © 2016 Magento. All rights reserved. * See COPYING.txt for license details.
*/
use Magento\Framework\Component\ComponentRegistrar;
ComponentRegistrar::register(ComponentRegistrar::MODULE, 'Autosynch_sale', __DIR__);

Autosynch \ Sale \ Observer \ OrderPlaceAfter.php

<?php
namespace Autosynch\Sale\Observer;
use Magento\Framework\Event\ObserverInterface;
class Observer implements ObserverInterface {

    protected $connector; public function __construct() { 
        $objectManager = \Magento\Framework\App\ObjectManager::getInstance(); 
    }

    public function execute(\Magento\Framework\Event\Observer $observer) { 
        $order = $observer->getEvent()->getOrder();
        $customerId = $order->getCustomerId();
        $order_status       = $order->getStatus();

        if($customerId){ // Order Criada
            define("getHost", "100.100.100.100");
            define("getUser", "username");
            define("getPassword", "password");
            define("getDB", "dbname");
            $mysqli = new mysqli(getHost, getUser, getPassword, getDB);
            $mysqli->select_db("dbname");

                if($order_status == 'processing'){
                    mysqli_query($mysqli, "INSERT INTO `test` (`id`, `test`) VALUES (NULL, '1')") or die(mysqli_error($mysqli));
                } else{
                    mysqli_query($mysqli, "INSERT INTO `test` (`id`, `test`) VALUES (NULL, '2')") or die(mysqli_error($mysqli));
                }
        } else{
        mysqli_query($mysqli, "INSERT INTO `test` (`id`, `test`) VALUES (NULL, '3')") or die(mysqli_error($mysqli));        
        }
    }
}

1 个答案:

答案 0 :(得分:0)

此代码是否抛出任何错误?如果是这样,您提供了吗? 另外,由于您使用的是magento,因此始终最好使用其自己的ORM而不是原始查询。在您的模块中,您可以在magento应用程序数据库中创建表,并创建模型来访问这些表。这是最好的方法!