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

React Native or Flutter in 2024

The mobile app development field has witnessed a rapid revolution over the past few years.…

15 hours ago

Magento 2: How To Call JS on the Checkout Page?

Hello Magento mates, Today we will learn to add a call JS on the checkout…

4 days ago

Boost Your SEM Game: Unveiling the Top 10 Tools for Marketers in 2024

Business survival in today’s digital world has become extremely difficult. Using traditional marketing techniques is…

5 days ago

Five Essential Payroll Compliance Tips for eCommerce Startups

Are you setting up a payroll system for your eCommerce startup? Ensuring compliance with myriad…

6 days ago

Optimizing Laravel Blade: Unlocking Advanced Fetcher Techniques

In the expansive universe of Laravel development, Blade serves as the stellar templating engine, propelling…

6 days ago

Magento 2: Add Quantity Increment and Decrement on Category Page

Hello Magento Friends, In this blog, we will discuss about adding quantity increment and decrement…

1 week ago