Hello Magento Folks!
In our Previous Blog we discussed How To Add Date of Birth Field in Customer Registration Form in Magento 2? today we will learn about How to add Status History Comment to the order by id in Magento 2?
Sometimes while doing customization we have need to add History Comment in order for doing that we need to use interface, Magento\Sales\Api\OrderStatusHistoryRepositoryInterface to add a comment.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 |
<?php namespace Webiators\CustomOrderComment\Block; use Magento\Sales\Api\OrderStatusHistoryRepositoryInterface; use Magento\Sales\Api\OrderRepositoryInterface; use Magento\Framework\Exception\NoSuchEntityException; use Magento\Sales\Api\Data\OrderStatusHistoryInterface; class CustomComent { /** @var OrderStatusHistoryRepositoryInterface */ private $orderStatusRepository; /** @var OrderRepositoryInterface */ private $orderRepository; public function __construct( OrderStatusHistoryRepositoryInterface $orderStatusRepository, OrderRepositoryInterface $orderRepository ) { $this->orderStatusRepository = $orderStatusRepository; $this->orderRepository = $orderRepository; } /** * add custom Comnnet to order History * * @param int $orderId * @return OrderStatusHistoryInterface|null */ public function addCustomOrderComment(int $orderId) { $order = $this->orderRepository->get($orderId); $orderHistory = null; if ($order) { $comment = $order->addStatusHistoryComment( 'This is custom order commnet to test' ); $orderHistory = $this->orderStatusRepository->save($comment); } return $orderHistory; } } |
By Adding Above code in any class of magento 2 and by passing order id in the above method you will be able to add any order comment in the comment history just like this.
1 2 |
$orderId = 1225; $orderHistoryComment= $block->addCustomOrderComment($orderId); |
I believe this blog helps you and was easy enough to make you understand. if you still have doubt please feel free to leave a comment below to discuss more.
Happy Coding
Thanks
Pingback:Magento Tech Digest #151 – Max Pronko