How To

Magento 2: Add Admin User name and Action name in Order Comment Section through Action Performed from Sales Order Grid

Hello Magento Friends,

Today we will learn about adding admin username and action name in the order comment section in Magento 2.

Magento 2 website may have more than one admin user. While executing orders, the admin user may change the order action from the sales order grid. But with this, the other admin is unaware of who has changed the order action.

To smoothen the admin communication, you can display the admin user name and action name in the order comments section based on the action performed from the sales order grid in Magento 2.

Let’s see how you can accomplish it.

Steps to Add Admin User name and Action name in Order Comment Section in Magento 2:

Step 1:  First, we need to create an “events.xml“ file inside our extension at the following path

app\code\Vendor\Extension\etc\adminhtml\

Then add the code as follows.

<?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="sales_order_save_after">
        <observer name="sales_order_save_after_comment_history_add" 
         instance="\Vendor\Extension\Observer\OrderSaveAfter" />
    </event>
</config>

Step 2:  After that, we need to create an “OrderSaveAfter.php” file inside our extension at the following path

app\code\Vendor\Extension\Observer\

And embed the code as given below.

<?php 
namespace Vendor\Extension\Observer;

use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\App\RequestInterface;
use Magento\Backend\Model\Auth\Session;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Sales\Api\OrderRepositoryInterface;
use Magento\Sales\Api\Data\OrderStatusHistoryInterface;
use Magento\Sales\Api\OrderStatusHistoryRepositoryInterface;

class OrderSaveAfter implements ObserverInterface
{
    protected $_request;
    protected $authSession;
    protected $orderStatusRepository;
    protected $orderRepository;
    
    public function __construct(
        RequestInterface  $request,
        Session $authSession,
        OrderStatusHistoryRepositoryInterface $orderStatusRepository,
        OrderRepositoryInterface $orderRepository
    )
    {
     $this->authSession = $authSession;
        $this->_request = $request;
        $this->orderStatusRepository = $orderStatusRepository;
        $this->orderRepository = $orderRepository;
    }

    public function execute(\Magento\Framework\Event\Observer $observer)
    {
         if($this->_request->getParam('selected'))
         {
          $selectedids = $this->_request->getParam('selected');
          foreach($selectedids as $orderids)
             {
                 $orderid = $orderids;
                 $this->addCommentToOrder($orderid);
          }
         }
         return $this;
    }
    public function addCommentToOrder($orderId)
    {
        $order = null;
        try
        {
            $order = $this->orderRepository->get($orderId);
        }
        catch (NoSuchEntityException $exception)
        {
            return false;
        }
        $orderHistory = null;
        if ($order)
        {
            $username = $this->authSession->getUser()->getUsername();
            $comment = $order->addStatusHistoryComment(
                      '<b>Admin User :</b> '.$username. " <b>Perform :</b> ".$order->getStatusLabel()
            );
            try
            {
                $orderHistory = $this->orderStatusRepository->save($comment);
            }
            catch (\Exception $exception)
            {
                return false;
            }
        }
        return $orderHistory;
    }
}

Conclusion:

This way you can easily add the admin username and action name in the order comment section based on the action performed in the sales order grid in Magento 2. If you have doubts, then let me know through the comment section. Stay in the know for more Magento 2 tutorials.

Happy Coding!

Click to rate this post!
[Total: 5 Average: 5]
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.🏏

View Comments

  • Let's now add the name of the person if they leave comments directly in the comment box. I added a Controller (AddComment.php) and di.xml to your module but it doesn't seem to work.

Recent Posts

How to Integrate ChatGPT with Laravel Application?

In this guide, we'll explore how to integrate ChatGPT, an AI-powered chatbot, with a Laravel…

13 hours ago

What are Net Sales? How to Calculate Your Net Sales?

In the world of business, understanding financial metrics is crucial for making informed decisions and…

3 days ago

Magento 2 Extensions Digest April 2024 (New Release & Updates)

Welcome to the MageComp Monthly Digest, where we bring you the latest updates, releases, and…

3 days ago

The ABCs of Geofencing: Definition, Features and Uses

In this era, businesses are always on the lookout for ways to engage with their…

4 days ago

How to Delete Product Variant in a Shopify Remix App using GraphQL Mutations?

Managing a Shopify store efficiently involves keeping your product catalog organized. This includes removing outdated…

4 days ago

6 Innovative Tools Revolutionizing E-Commerce Operations

E-commerce has transformed the way consumers shop for products and services and interact with businesses.…

7 days ago