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

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…

2 days 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…

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

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

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

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

1 week ago