How To

Magento 2: How to Bind Custom Text while Add Comment in Admin Sales Order View

Hello Magento Friends,

Today we will discuss Magento 2: How to Bind Custom Text while Add Comment in Admin Sales Order View.

Customization is the central part of Magento 2. Store admin can customize anything as per the business requirement. Customizing the admin sales order view helps the admin to efficiently fulfill orders leading to improved user experience.

If you want to add custom text while adding comment in the admin sales order view in Magento 2, you can use the below steps.

Steps to Bind Custom Text while Add Comment in Admin Sales Order View in Magento 2:

Step 1:  Firstly, we need to create a “di.xml“ file inside our extension at the following path.

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

And then add the code as follows

<?xml version="1.0"?>
<config xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xsi:noNamespaceSchemaLocation='../../../../../lib/internal/Magento/Framework/ObjectManager/etc/config.xsd'>
    <type name='Magento\Sales\Controller\Adminhtml\Order\AddComment'>
        <plugin name='order_add_comment_plugin' type='Vendor\Extension\Plugin\Adminhtml\Order\OrderAddComment' sortOrder='10' disabled='false' />
    </type>
</config>

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

app\code\Vendor\Extension\Plugin\Adminhtml\Order

Then add the below code snippet

<?php 
namespace Vendor\Extension\Plugin\Adminhtml\Order;

use Magento\Framework\App\RequestInterface;
use Magento\Backend\Model\Auth\Session;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Framework\Exception\InputException;
use Magento\Sales\Api\OrderRepositoryInterface;
use Magento\Sales\Api\Data\OrderStatusHistoryInterface;
use Magento\Sales\Api\OrderStatusHistoryRepositoryInterface;
use Magento\Framework\Registry;
use Magento\Framework\View\Result\PageFactory;
use Magento\Framework\Controller\Result\JsonFactory;
use Magento\Framework\Controller\Result\Redirect;
use Magento\Sales\Model\Order\Email\Sender\OrderCommentSender;
use Magento\Framework\AuthorizationInterface;

class OrderAddComment
{
    public const ADMIN_RESOURCE = 'Magento_Sales::comment';
    public const ADMIN_SALES_EMAIL_RESOURCE = 'Magento_Sales::emails';

    protected $_request;
    protected $authSession;
    protected $orderStatusRepository;
    protected $orderRepository;
    protected $_coreRegistry = null;
    protected $resultPageFactory;
    private $resultJsonFactory;
    protected $orderCommentSender;
    protected $_authorization;

    public function __construct(
        RequestInterface  $request,
        Session $authSession,
        OrderStatusHistoryRepositoryInterface $orderStatusRepository,
        OrderRepositoryInterface $orderRepository,
        Registry $coreRegistry,
        PageFactory $resultPageFactory,
        JsonFactory $resultJsonFactory,
        Redirect $resultRedirectFactory,
        OrderCommentSender $orderCommentSender,
        AuthorizationInterface $authorization
    )
    {
     $this->authSession = $authSession;
        $this->_request = $request;
        $this->orderStatusRepository = $orderStatusRepository;
        $this->orderRepository = $orderRepository;
        $this->_coreRegistry = $coreRegistry;
        $this->resultPageFactory = $resultPageFactory;
        $this->resultJsonFactory = $resultJsonFactory;
        $this->resultRedirectFactory = $resultRedirectFactory;
        $this->orderCommentSender = $orderCommentSender;
        $this->_authorization = $authorization;
    }

    public function aroundExecute(\Magento\Sales\Controller\Adminhtml\Order\AddComment $subject, callable $proceed)
    {
          $order = $this->_initOrder();
         if ($order)
                {
             try
                    {
                 $data = $subject->getRequest()->getPost('history');

                 if (empty($data['comment']) && $data['status'] == $order->getDataByKey('status'))
                        {
                     throw new \Magento\Framework\Exception\LocalizedException(
                         __('The comment is missing. Enter and try again.')
                     );
                 }

                 $order->setStatus($data['status']);
                 $notify = $data['is_customer_notified'] ?? false;
                 $visible = $data['is_visible_on_front'] ?? false;

                 if ($notify && !$this->_authorization->isAllowed(self::ADMIN_SALES_EMAIL_RESOURCE))
                        {
                     $notify = false;
                 }

                 $comment = trim(strip_tags($data['comment']));
                 $username = $this->authSession->getUser()->getUsername();
                 $history = $order->addStatusHistoryComment($comment.'<br><b>Admin User :</b> '.$username, $data['status']);
                 $history->setIsVisibleOnFront($visible);
                 $history->setIsCustomerNotified($notify);
                 $history->save();

                 $order->save();
                
                 $this->orderCommentSender->send($order, $notify, $comment);

                 return $this->resultPageFactory->create();
             }
                    catch (\Magento\Framework\Exception\LocalizedException $e)
                    {
                 $response = ['error' => true, 'message' => $e->getMessage()];
             }
                    catch (\Exception $e)
                    {
                 $response = ['error' => true, 'message' => __('We cannot add order history.')];
             }
             if (is_array($response))
                    {
                 $resultJson = $this->resultJsonFactory->create();
                 $resultJson->setData($response);
                 return $resultJson;
             }
       }
              return $this->resultRedirectFactory->create()->setPath('sales/*/');
    }
    
    public function _initOrder()
    {
        $id = $this->_request->getParam('order_id');
        try
        {
            $order = $this->orderRepository->get($id);
        }
        catch (NoSuchEntityException $e)
        {
            return false;
        }
        catch (InputException $e)
        {
            return false;
        }
        $this->_coreRegistry->register('sales_order', $order);
        $this->_coreRegistry->register('current_order', $order);
        return $order;
    }
}

Output:

Conclusion:

Implementing the above steps correctly, you can Bind Custom Text while Add Comment in Admin Sales Order View in Magento 2. Also, add custom button in the admin sales order view page. Share the tutorial with your friends and stay connected with us!

Happy Coding!

Click to rate this post!
[Total: 1 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

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.…

6 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