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

Generating Thumbnails with Spatie Media Library in Laravel 11: A Step-by-Step Guide

Generating image thumbnails is a common requirement in web applications, especially when handling media-heavy content.…

3 hours ago

Enhancing Web Application Security with Laravel’s Built-In Features

In today’s digital landscape, web application security is paramount. As a powerful PHP framework, Laravel…

1 day ago

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

October was an exciting month for MageComp! From significant updates across our Magento 2 extension…

1 day ago

Improving Error Handling and Transition Management in Remix with useRouteError and useViewTransitionState

In modern web development, seamless navigation and state management are crucial for delivering a smooth…

1 week ago

Magento Open Source 2.4.8-Beta Release Notes

Magento Open Source 2.4.8 beta version released on October  8, 2024. The latest release of…

1 week ago

How to Create Catalog Price Rule in Magento 2 Programmatically?

Hello Magento Friends, Creating catalog price rules programmatically in Magento 2 can be a valuable…

1 week ago