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

How to Bind Custom Text while Add Comment in Admin Sales Order View in m2

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:

custom text

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!

Previous Article

Biggest Black Friday Cyber Monday Offers | BFCM 2022 Deals

Next Article

How to Remove Language Switcher in Magento 2

View Comments (2)

Leave a Comment

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

Get Connect With Us

Subscribe to our email newsletter to get the latest posts delivered right to your email.
Pure inspiration, zero spam ✨