Question

I want to load the data of an order with the incremental id after placing an order. I am getting the incremental id in the data array after placing an order, but cant load any orders with it.

My Observer:

public function execute(\Magento\Framework\Event\Observer $observer)
    {
        $order = $observer->getEvent()->getOrder()->getData();
        $incrementId = $order['increment_id'];
        $this->helper->writeShp($incrementId);
    }

WriteShp():

public function writeShp($incrementId){
        try {
            $this->logger->info($incrementId);
            $order = $this->orderFactory->create()->loadByIncrementId($incrementId);
            $this->logger->info('order', array('order', $order));
        } catch (\Exception $e) {
            $this->logger->critical($e->getMessage());
        }

The following is getting logged:

[2019-03-07 14:54:02] main.INFO: 000000040 [] []
[2019-03-07 14:54:02] main.CRITICAL: No such entity with orderId =  [] []

The weird thing is the [ ] [ ] behind the incrementId. Could this be the problem?

I have tried this:

$onlyId = preg_replace("/[^0-9]/", '', $incrementId);

but still there would be [ ] [ ] behind the incrementid. Imploding also didn't work, it said it wasnt an array.

Was it helpful?

Solution

In the event sales_order_place_after the order you try to load isn't stored in the database at that moment. That's why loadByIncrementId() fails. The save() call comes right after that event.

So you can either take the $order object as it will be saved, that's the parameter passed to the observer or take a later event like sales_order_save_after or even sales_order_save_commit_after if you really want to load the data from database (for what ever reason). In both cases you will have for example the the order id.

Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top