How To

How to Add Comments to Order Programmatically After Place Order from Frontend in Magento 2

Hello Magento Friends,

In this Magento 2 tutorial guide, I will explain How to Add Comments to Order Programmatically After Place Order from Frontend in Magento 2.

In Magento 2, the ability to add comments or notes to an order programmatically after it has been placed from the front end can be quite useful for various purposes, such as providing additional instructions, clarifications, or internal communication.

Let’s see How to Add Comments to Order Programmatically After Place Order from Frontend in Magento 2.

Steps to Add Comments to Order Programmatically After Place Order from Frontend in Magento 2:

Step 1: Create a file at app\code\Vendor\Extension\etc\events.xml and add the below code.

<?xml version="1.0"?>

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
    <event name="checkout_onepage_controller_success_action">
        <observer name="order_observer" instance="\Vendor\Extension\Observer\OrderObserver"/>
    </event>
</config>

Step 2: Create a file at app\code\Vendor\Extension\Observer\OrderObserver.php and add the below code.

<?php

namespace Vendor\Extension\Observer;

use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;
use Magento\Sales\Api\OrderRepositoryInterface;
use Magento\Sales\Model\Order\Status\HistoryFactory;

class OrderObserver implements ObserverInterface
{
     protected $orderRepository;

     protected $orderStatusHistoryFactory;
    
    public function __construct(
        OrderRepositoryInterface $orderRepository,
        HistoryFactory $orderStatusHistoryFactory
    )
    {
        $this->orderRepository = $orderRepository;
        $this->orderStatusHistoryFactory = $orderStatusHistoryFactory;
    }

    public function execute(Observer $observer)
    {
       $order = $observer->getEvent()->getOrder();
        $comment = "Your comment goes here.";
        $this->addCommentToOrder($order->getId(), $comment);
        return $this;
    }

    public function addCommentToOrder($orderId, $comment)
    {
        try {
        $order = $this->orderRepository->get($orderId);
        $statusHistory = $this->orderStatusHistoryFactory->create();
        $statusHistory->setComment(
                       __('Comment: %1.', $comment)
                   );
        $statusHistory->setEntityName(\Magento\Sales\Model\Order::ENTITY);
        $statusHistory->setStatus($order->getStatus());
        $statusHistory->setIsCustomerNotified(false)->setIsVisibleOnFront(false);
        $order->addStatusHistory($statusHistory);
        $this->orderRepository->save($order);
        } catch (\Exception $e) {
            throw new LocalizedException(__("Failed to add the comment to the order: %1", $e->getMessage()));
        }
    } 
}

Output:

Go to the order view page on the front end, where you should now see a comment form. Add a comment and click the “Submit Comment” button. The comment should be added to the order’s status history.

Conclusion:

By following these steps, you can enhance your store’s communication and organization by enabling the addition of comments or notes to orders. This functionality can be particularly helpful for keeping track of special instructions, updates, or any other relevant information associated with each order. You can also use Magento 2 Order Comments Extension to allow customers to add a comment at the checkout page and manage it successfully from the backend.

Share the tutorial with your friends and stay in touch with us for Magento solutions.

Happy Coding!

Click to rate this post!
[Total: 10 Average: 1]
Dhiren Vasoya

Dhiren Vasoya is a Director and Co-founder at MageComp, Passionate ?️ Certified Magento Developer?‍?. He has more than 9 years of experience in Magento Development and completed 850+ projects to solve the most important E-commerce challenges. He is fond❤️ of coding and if he is not busy developing then you can find him at the cricket ground, hitting boundaries.?

Recent Posts

How to Add Tooltip in Checkout Shipping Field in Magento 2?

Hello Magento Friends, In today’s blog, I will explain How to Add Tooltip in Checkout…

8 hours ago

How to Integrate and Use MongoDB with Laravel?

MongoDB is a popular NoSQL database that offers flexibility and scalability when handling modern web…

1 day ago

NodeJS | Callback Function

In NodeJS, callbacks empower developers to execute asynchronous operations like reading files, handling requests, and…

2 days ago

How to Show SKU in Order Summary in Magento 2?

Hello Magento Friends, In today’s blog, we will learn How to Show SKU in Order…

4 days ago

Best Colors to Use for CTA Buttons

The "Buy Now" and "Add to Cart" buttons serve as the primary call-to-action (CTA) elements…

6 days ago

Magento 2: How to Save Custom Field Value to quote_address for Multi-Shipping Orders

Hello Magento Friends, In Magento 2, the checkout process allows customers to choose multiple shipping…

1 week ago