Question

In admin panel Sales->Orders section, while viewing the order, It show order information like below,How to add comment programatically.... And it needs to save (sale_order_status_history) table Suggest a solution.. enter image description here

Was it helpful?

Solution

$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.

OTHER TIPS

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!!!

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

Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top