8

I need to change the order status and order status history comment based on the last value of the status, currently i've set order status and comment status like this:

$event = $observer->getEvent();
$order = $event->getOrder();
// need to check the previous order status history comment
$history = $order->addStatusHistoryComment('', $order->getStatus());
$history->save();
// need to check last order status
$order->setData('status', $order->getStatus())->getResource()->saveAttribute($order, 'status'); 
1
  • which observer you are using there?
    – HaFiz Umer
    Nov 25, 2019 at 6:33

2 Answers 2

12

To retrieve latest order's comment history you can do following:

$histories = $order->getStatusHistories();
/** @var OrderStatusHistoryInterface $caseCreationComment */
$latestHistoryComment = array_pop($histories);
$comment = $latestHistoryComment->getComment();
$status = $latestHistoryComment->getStatus();

To add new history comment to the created order you can use Magento\Sales\Model\Order\Status\HistoryFactory and \Magento\Sales\Api\OrderStatusHistoryRepositoryInterface:

/** @var \Magento\Sales\Api\Data\OrderStatusHistoryInterface $history */
$history = $historyFactory->create();
$history->setParentId($order->getId())
    ->setComment($comment)
    ->setEntityName('order')
    ->setStatus($status);

$historyRepository->save($history);
1
  • thank you.. helpful Feb 20, 2020 at 9:16
2

Before adding the new status history comment you can get the previous one like

$statusHistoryItem = $order->getStatusHistoryCollection()->getFirstItem();

$status = $statusHistoryItem->getStatusLabel();

$comment = $statusHistoryItem->getComment();
2
  • If I wanted to change the order comments ordering from descending order (most recent on top) to ascending order (first comment on top) would this be possible using these methods? and if so, where would I do it? Thanks for the insight!
    – ne0nlight
    Jul 12, 2019 at 17:54
  • @Nikolas it is already most recent on top : $this->_statusHistory = Mage::getResourceModel('sales/order_status_history_collection') ->setOrderFilter($this) ->setOrder('created_at', 'desc') ->setOrder('entity_id', 'desc'); Aug 19, 2019 at 13:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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