1

I want to show the admin user name on change order status in order comment history in bulk or single order, using a single event or plugin Magento 2.3.5p1 Community edition

Any help highly appreciated

Thanks

1

There is an already answer for this question. Please refer the link

How to adding sender's name to order comments in Magento2 admin?

Below is a working sample tested in Magento 2.3.5-p1

app/code/[Vendor]/[ModuleName]/etc/adminhtml/di.xml

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <preference for="Magento\Sales\Controller\Adminhtml\Order\AddComment" type="[Vendor]\[ModuleName]\Controller\Adminhtml\Order\AddComment" />
</config>

app/code/[Vendor]/[ModuleName]/Controller/Adminhtml/Order/AddComment.php

<?php
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */
namespace [Vendor]\[ModuleName]\Controller\Adminhtml\Order;

use Magento\Framework\App\Action\HttpPostActionInterface;
use Magento\Sales\Model\Order\Email\Sender\OrderCommentSender;

use Magento\Backend\App\Action;


use Magento\Sales\Api\OrderManagementInterface;
use Magento\Sales\Api\OrderRepositoryInterface;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Framework\Exception\InputException;
use Psr\Log\LoggerInterface;

/**
 * Class AddComment
 */
class AddComment extends \Magento\Sales\Controller\Adminhtml\Order implements HttpPostActionInterface
{
     /**
     * Authorization level of a basic admin session
     *
     * @see _isAllowed()
     */
    const ADMIN_RESOURCE = 'Magento_Sales::comment';

    /**
     * Core registry
     *
     * @var \Magento\Framework\Registry
     */
    protected $_coreRegistry = null;

    /**
     * @var \Magento\Framework\App\Response\Http\FileFactory
     */
    protected $_fileFactory;

    /**
     * @var \Magento\Framework\Translate\InlineInterface
     */
    protected $_translateInline;

    /**
     * @var \Magento\Framework\View\Result\PageFactory
     */
    protected $resultPageFactory;

    /**
     * @var \Magento\Framework\Controller\Result\JsonFactory
     */
    protected $resultJsonFactory;

    /**
     * @var \Magento\Framework\View\Result\LayoutFactory
     */
    protected $resultLayoutFactory;

    /**
     * @var \Magento\Framework\Controller\Result\RawFactory
     */
    protected $resultRawFactory;

    /**
     * @var OrderManagementInterface
     */
    protected $orderManagement;

    /**
     * @var OrderRepositoryInterface
     */
    protected $orderRepository;

    /**
     * @var LoggerInterface
     */
    protected $logger;

    protected $authSession;

    public function __construct(
        Action\Context $context,
        \Magento\Framework\Registry $coreRegistry,
        \Magento\Framework\App\Response\Http\FileFactory $fileFactory,
        \Magento\Framework\Translate\InlineInterface $translateInline,
        \Magento\Framework\View\Result\PageFactory $resultPageFactory,
        \Magento\Framework\Controller\Result\JsonFactory $resultJsonFactory,
        \Magento\Framework\View\Result\LayoutFactory $resultLayoutFactory,
        \Magento\Framework\Controller\Result\RawFactory $resultRawFactory,
        OrderManagementInterface $orderManagement,
        OrderRepositoryInterface $orderRepository,
        LoggerInterface $logger,
        \Magento\Backend\Model\Auth\Session $authSession
    ) {
        $this->authSession = $authSession;
        parent::__construct($context, $coreRegistry,$fileFactory,$translateInline,$resultPageFactory,$resultJsonFactory,$resultLayoutFactory,$resultRawFactory,$orderManagement,$orderRepository,$logger);
    }


    /**
     * Add order comment action
     *
     * @return \Magento\Framework\Controller\ResultInterface
     */
    public function execute()
    {
        
        $order = $this->_initOrder();
        if ($order) {
            try {
                $data = $this->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.')
                    );
                }

                $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;
                }

                $username = $this->authSession->getUser()->getUsername();
                $append = " (by ".$username.")";

                $history = $order->addStatusHistoryComment($data['comment'].$append, $data['status']);
                $history->setIsVisibleOnFront($visible);
                $history->setIsCustomerNotified($notify);
                $history->save();

                

                $comment = trim(strip_tags($data['comment']));

                $order->save();
                /** @var OrderCommentSender $orderCommentSender */
                $orderCommentSender = $this->_objectManager
                    ->create(\Magento\Sales\Model\Order\Email\Sender\OrderCommentSender::class);

                $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/*/');
        return parent::execute();
    }
}

Run the below commands after modifying the files

php bin/magento setup:di:compile
php bin/magento cache:flush
9
  • not working, i tried! – Munesh Jalwani Sep 28 '20 at 10:15
  • @MuneshJalwani Updated the answer – Rinto George Sep 28 '20 at 11:06
  • @RintoGeorge Hi, I tried this solution, but I get this error Fatal error: Uncaught Error: Undefined class constant 'ADMIN_SALES_EMAIL_RESOURCE' in /Users/jonathanhelvey/ULM-NewSite/httpdocs/app/code/UpperLimits/AddAdminNametoComment/Controller/Adminhtml/Order/AddComment.php:126 Stack trace: #0 /Users/jonathanhelvey/ULM-NewSite/httpdocs/vendor/magento/framework/App/Action/Action.php(108): UpperLimits\AddAdminNameToComment\Controller\Adminhtml\Order\AddComment- – Jonathan Apr 1 at 16:15
  • When I checkmark "Notify Customer By Email" Is when Error is thrown. NewSite/httpdocs/app/code/UpperLimits/AddAdminNametoComment/Controller/Adminhtml/Order/AddComment.php on line 126 Also, Posting comment does work if I do Not checkmark "Notify Customer By Email", however, after posting comment I have to refresh page, for it to show, otherwise notes is missing until browser refresh. Just curious if you know a solution to help fix. Thank you for any help. – Jonathan Apr 1 at 16:58
  • 1
    @Jonathan That means there are errors on your save function, enable the error log or check in debug logs – Rinto George Apr 6 at 14:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.