4

In admin panel Sales->Orders section, while viewing the order, it shows order information like below.

How to add comment programmatically? It needs to save (sale_order_status_history) table

enter image description here

2

4 Answers 4

9
$orderId = $orderId;
    $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
    $order = $objectManager->create('\Magento\Sales\Model\Order')->load($orderId);
    $order->addStatusHistoryComment('This comment is programatically added to last order in this Magento setup');
    $order->save();

you can also user magento repo object as well.

2
  • how to pass same comment dynamically
    – Mahi M
    Feb 5, 2018 at 14:01
  • See \Magento\Sales\Model\Order::addCommentToStatusHistory() because "addStatusHistoryComment" is deprecated already Jun 29, 2021 at 4:37
7

addStatusHistoryComment is deprecated, use addCommentToStatusHistory instead.

Here is the sample code:

protected $orderRepository;

public function __construct(
    ...
    \Magento\Sales\Model\OrderRepository $orderRepository
    ...
) {
    $this->orderRepository = $orderRepository;
}

public function saveOrder($orderId)
{
    $order = $this->orderRepository->get($orderId);
    $order->addCommentToStatusHistory('Test Order Comment');
    $this->orderRepository->save($order);
}

Check for more details: \Magento\Sales\Model\Order::addCommentToStatusHistory

1

You can also try this code.Please create a sample file in the root and paste below code.and run this file.

use \Magento\Framework\App\Bootstrap;

include('./app/bootstrap.php');
$mage_bootstrap = Bootstrap::create(BP, $_SERVER);
$object_Manager = $mage_bootstrap->getObjectManager();
$site_url = \Magento\Framework\App\ObjectManager::getInstance();
$storeManager = $site_url->get('\Magento\Store\Model\StoreManagerInterface');
$mediaurl= $storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA);
$state = $object_Manager->get('\Magento\Framework\App\State');
$state->setAreaCode('frontend');

$orderId = 15;

$order = $object_Manager->create('\Magento\Sales\Model\Order')->load($orderId); 
$order->addStatusToHistory('pending', 'Put your comment here', false);
$order->save();

Once you run this file you can see the updated status from the admin. Thanks!!!

0
0

If you do not want to save the order and use \Magento\Sales\Model\Order::addCommentToStatusHistory method - it is also possible with:

   $history = $this->historyFactory->create();
   $history->setStatus($order->getStatus())
      ->setComment($message)
      ->setEntityName($order->getEntityType())
      ->setIsVisibleOnFront(false)
      ->setOrder($order);
   $history->save();

Not a best practice though, but working.

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