Magento 2 – Get Last Order Status History Comment and Order Status

historymagento-2.1order-statussales-order

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'); 

Best Answer

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);