Magento 2 – Retrieve Order Comment Field Details from Database

magento2.2PHPsales-order

In admin panel Sales->Orders section, while viewing the order, It show order information like below
enter image description here

I need to fetch the comment details from core table (sale_order_status_history).and want to show in frontend. Please provide a solution to get comment field details and what are the files needed to achieve this.

For reference the image is below,
enter image description here

I have created Block file but it returns empty page

<?php

namespace XXX\SalesOrder\Block;

use Magento\Framework\View\Element\Template\Context;
use Magento\Framework\View\Element\Template;
use Magento\Sales\Model\OrderFactory as OrderFactory;

class Hello extends Template
{

    protected $orderFactory;

    public function __construct(
    \Magento\Framework\View\Element\Template\Context $context, OrderFactory $orderFactory
    )
    {
        $this->orderFactory = $orderFactory;
        parent::__construct($context);
    }

    public function getCollection()
    {

        $order = $this->orderFactory->create()->load('1');


        $orderCommentHistory = $order->getStatusHistoryCollection();

      echo '<pre>';
      print_r($orderCommentHistory);
    }

}

Best Answer

If you have $order object then you can easily get the order comment history by,

$order->getStatusHistoryCollection()

If you don't have $order object then you can use like this,

use Magento\Sales\Model\OrderFactory as OrderFactory;

protected $orderFactory;


public function __construct(
    ...
    OrderFactory $orderFactory  
    ....
) {
    ....
    $this->orderFactory = $orderFactory;    
    ....
}


$order = $this->orderFactory->create()->load('YOUR_ORDER_ID');
$orderCommentHostory=$order->getStatusHistoryCollection();

EDIT If you need order comment then please try this,

$orderComment = [];
foreach ($order->getStatusHistoryCollection() as $status) {
    if ($status->getComment()) {
        $orderComment[] = $status->getComment();
    }
}

At the end, you have all order comments in $orderComment

Related Topic