How To Bind Custom Text While Adding A Comment In Sales Order View In Magento 2      

Hello Everyone,       

In this blog, we will learn about how to Bind Custom Text while Adding Comment in Sales Order View in Magento 2.

Store Admin can customize anything as per requirements.

Without wasting your time, let us guide you straight away. Follow the easy step given below to Bind Custom Text while Add Comment in Sales Order View in Magento 2.

STEPS FOR BIND CUSTOM TEXT IN SALES ORDER VIEW IN MAGENTO 2

Step 1: Create di.xml file

app/code/Vendor/Extension/etc/adminhtml/di.xml

<?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' type='Vendor\Extension\Plugin\Adminhtml\Order\AddComment'/>

    </type>

</config>

Step 2: Create AddComment.php file

app/code/Vendor/Extension/Plugin/Adminhtml/Order/AddComment.php

<?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 AddComment
{
    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;
    protected $resultRedirectFactory;

    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']));
	                $adminusername = $this->authSession->getUser()->getUsername();
	                $history = $order->addStatusHistoryComment($comment.'<br><b>Admin User :</b> '.$adminusername, $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;
    }
}

Step 3: Finally run the below commands

$ php bin/magento cache:clean

$ php bin/magento cache:flush

Step 4: Output:

Final Thoughts:

So this was the easiest way which we have told you in this blog. This is how you can Bind Custom Text while Adding a Comment in Sales Order View in Magento 2. Hope you liked the blog.

So quickly go to the comment box and tell me how you like this blog?

Stay tuned with us on our site to get new updates of Magento.

Thanks for reading and visiting our site.

How useful was this post?

Click on a star to rate it!

Average rating 5 / 5. Vote count: 1

No votes so far! Be the first to rate this post.

Leave a Reply

Your email address will not be published. Required fields are marked *