Magento – Force order status and state to processing after creating shipment using observer

magento2order-statussales-ordershipment

I created an observer to change my order status after creating shipment like this:

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="sales_order_shipment_save_after">
        <observer instance="Namespace\Module\Observer\Sales\OrderShipmentSaveAfter" name="namespace_module_observer_sales_ordershipmentsaveafter_sales_order_shipment_save_after"/>
    </event>
</config>

app/code/Namespace/Module/Observer/Sales/OrderShipmentSaveAfter.php

public function execute(
    \Magento\Framework\Event\Observer $observer
) {
  $shipment = $observer->getEvent()->getShipment();
  $order = $shipment->getOrder();
  $orderState = Order::STATE_PROCESSING;
  $status = 'delivery';
  $order->setState($orderState)->setStatus($status);
  $order->save();
}

If i create an order then create a shipment the status will be delivery, and the state will be processing, but if i create invoice first then create shipment for my order, the order status and state will become complete and

Best Answer

When you save data from your order model, i think magento will do some kind of validation for your order state and status, to come up with your trouble run this function after you save the order:

    public function updateOrderRaw($orderId){
      $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
      $resource = $objectManager->get('Magento\Framework\App\ResourceConnection');
      $connection = $resource->getConnection();
      $tableName = $resource->getTableName('sales_order');
      $sql = "UPDATE " . $tableName . " SET status = 'delivery', state = 'processing' WHERE entity_id = " . $orderId;
      $connection->query($sql);
    }

the above function will run sql query to update the order status and state from sales_order table

Related Topic