0

I've noticed that when an order goes from Pending to Processing there is no entry created in sales_order_status_history. This is a change from Magento 1, which kept a history entry for every status change. We need to track the time in processing for every order, so it would be helpful to get a timestamp for when each order went into that status. How would I go about having a comment added to the comment history automatically when any status change happens, with the status that it was changed to?

1 Answer 1

0

To achieve this functionality you can use the magento observers:

sales_order_save_after: the event is triggered after an order is saved. It can be used to perform checks for order status updates.

create an observer and use the below code in execute method

public function execute(\Magento\Framework\Event\Observer $observer)
{
   $order = $observer->getEvent()->getOrder();
   
   $orderId= $order->getId(); 
   $this->logger->info('Data:: order status ' . $order->getStatus()); 

    $comment= "order status updated to ". $order->getState();
    try {
    $order = $this->orderRepository->get($orderId);
    $statusHistory = $this->orderStatusHistoryFactory->create();
    $statusHistory->setComment(
                   __('Comment: %1.', $comment)
               );
    $statusHistory->setEntityName(\Magento\Sales\Model\Order::ENTITY);
    $statusHistory->setStatus($order->getStatus());
    $statusHistory->setIsCustomerNotified(false)->setIsVisibleOnFront(false);
    $order->addStatusHistory($statusHistory);
    $this->orderRepository->save($order);
    } catch (\Exception $e) {
        throw new LocalizedException(__("Failed to add the comment to the order: %1", $e->getMessage()));
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.