Magento2 | PWA | GraphQL

Magento2 Add New Button on Sales Order View Page and Submit Form for your custom task.


In this post, We will check how to add new button on sales order view page and submit any form for your custom task like sending SMS messages for your order and fill up any necessary form information and send it for the further process.

Let's start it by creating custom extension. 

Find Complete module files on Github.

Create folder inside app/code/Magelearn/OrderPopup

Add registration.php file in it:
<?php
\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::MODULE,
    'Magelearn_OrderPopup',
    __DIR__
);
Add composer.json file in it:
{
    "name": "magelearn/module-orderpopup",
    "description": "",
    "type": "magento2-module",
    "license": "proprietary",
    "authors": [
        {
            "name": "Mage2Gen",
            "email": "info@mage2gen.com"
        }
    ],
    "minimum-stability": "dev",
    "require": {},
    "autoload": {
        "psr-4": {
            "Magelearn\\OrderPopup\\": ""
        },
        "files": [
            "registration.php"
        ]
    }
}
Add etc/module.xml file in it:
<?xml version="1.0" ?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
	<module name="Magelearn_OrderPopup" setup_version="1.0.0">
		<sequence>
			<module name="Magento_Sales"/>
		</sequence>
	</module>
</config>
Now Create your di.xml file inside app/etc and use plugin method to add button HTML code on sales order view page.
<?xml version="1.0" ?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
	<type name="Magento\Sales\Block\Adminhtml\Order\View">
		<plugin disabled="false" name="Magelearn_OrderPopup_Plugin_Magento_Sales_Block_Adminhtml_Order_View" sortOrder="10" type="Magelearn\OrderPopup\Plugin\Magento\Sales\Block\Adminhtml\Order\View"/>
	</type>
</config>
Now create plugin file View.php inside app/code/Magelearn/OrderPopup/Plugin/Magento/Sales/Block/Adminhtml/Order
<?php

namespace Magelearn\OrderPopup\Plugin\Magento\Sales\Block\Adminhtml\Order;

/**
 * Class View
 *
 * @package Magelearn\OrderPopup\Plugin\Magento\Sales\Block\Adminhtml\Order
 */
class View
{

    public function beforeSetLayout(
        \Magento\Sales\Block\Adminhtml\Order\View $subject,
        $layout
    ) {
        $subject->addButton(
            'sendordersms',
            [
                'label' => __('Create Warranty Order'),
                'onclick' => "",
                'class' => 'action-default action-warranty-order',
            ]
        );
        return [$layout];
    }

    public function afterToHtml(
        \Magento\Sales\Block\Adminhtml\Order\View $subject,
        $result
    ) {
        if($subject->getNameInLayout() == 'sales_order_edit'){
            $customBlockHtml = $subject->getLayout()->createBlock(
                \Magelearn\OrderPopup\Block\Adminhtml\Order\ModalBox::class,
                $subject->getNameInLayout().'_modal_box'
            )->setOrder($subject->getOrder())
                ->setTemplate('Magelearn_OrderPopup::order/modalbox.phtml')
                ->toHtml();
            return $result.$customBlockHtml;
        }
        return $result;
    }
}
Now create template file modalbox.phtml inside app/code/Magelearn/OrderPopup/view/adminhtml/templates/order/modalbox.phtml
<?php
/**
 * @var $block \Magelearn\OrderPopup\Block\Adminhtml\Order\ModalBox
 */
?>
<div id="popup-modal" style="display: none">
	<p><?= $block->escapeHtml($block->getInfo())?></p>
<form action="<?= $block->escapeUrl($block->getFormUrl())?>" method="post" id="order-view-add-warranty-form"> <input name="firstname" type="text"> <input name="lastname" type="text"> <input name="phone" type="text"> <input name="bookingTime" type="date"> <input type="button" value="Submit" id="order-view-add-warranty"> </form> </div> <script> require( [ 'jquery', 'Magento_Ui/js/modal/modal' ], function ( $, modal ) { var options = { type: 'popup', responsive: true, innerScroll: true, title: 'Modal Title', modalClass: 'custom-modal', buttons: [{ text: $.mage.__('Close'), class: '', click: function () { this.closeModal(); } }] }; var popup = modal(options, $('#popup-modal')); $("#sendordersms").click(function() { $("#popup-modal").modal('openModal'); }); $('#order-view-add-warranty').click(function () { $('#order-view-add-warranty-form').append($('<input>', { 'name': 'form_key', 'value': window.FORM_KEY, 'type': 'hidden' })); $('#order-view-add-warranty-form').submit(); }); } ); </script>
Now, Create Block file ModalBox.php inside Block/Adminhtml/Order/
<?php

namespace Magelearn\OrderPopup\Block\Adminhtml\Order;

/**
 * Class ModalBox
 *
 * @package Magelearn\OrderPopup\Block\Adminhtml\Order
 */
class ModalBox extends \Magento\Backend\Block\Template
{
    /**
     * Constructor
     *
     * @param \Magento\Backend\Block\Template\Context  $context
     * @param array $data
     */
    public function __construct(
        \Magento\Backend\Block\Template\Context $context,
        array $data = []
    ) {
        parent::__construct($context, $data);
    }

    /**
     * @return string
     */
    public function getInfo()
    {
        //Your block cod
        return __('My Title!! ');
    }
    public function getFormUrl()
    {
        $orderId = false;
        if($this->hasData('order')){
            $orderId = $this->getOrder()->getId();
        }
        return $this->getUrl('orderpopup/order/order',[
            'order_id' => $orderId
        ]);
    }
}
here in block file getFormUrl() function, we have give a link for form action. Which call to route (controller) file.

Create routes.xml file inside app/etc
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">
    <router id="admin">
        <route id="orderpopup" frontName="orderpopup">
            <module name="Magelearn_OrderPopup"/>
        </route>
    </router>
</config>
Now Create, controller file Order.php inside Controller/Adminhtml/Order/
<?php

namespace Magelearn\OrderPopup\Controller\Adminhtml\Order;

use Magento\Backend\App\Action;
use Magento\Backend\App\Action\Context;
use Magento\Framework\App\Action\HttpPostActionInterface;
use Magento\Framework\App\ResponseInterface;
use Magento\Framework\View\Result\Page;
use Magento\Framework\View\Result\PageFactory;
use Magento\Sales\Controller\Adminhtml\Order as AdminOrder;

class Order extends AdminOrder implements HttpPostActionInterface
{
    /**
     * Changes ACL Resource Id
     */
    const ADMIN_RESOURCE = 'Magento_Sales::hold';
    /**
     * @inheritDoc
     */
    public function execute()
    {
        $resultRedirect = $this->resultRedirectFactory->create();

        $order = $this->_initOrder();
        if ($order) {
            $post = $this->getRequest()->getPostValue();
			
			//$phone = $this->getRequest()->getParam('phone'); // example to get data with getParam() function
			//echo $phone;exit;
            //Put your custom logic here::
            
            $resultRedirect->setPath('sales/order/view', ['order_id' => $order->getId()]);
            return $resultRedirect;
        }
        $resultRedirect->setPath('sales/*/');
        return $resultRedirect;
    }
}
After adding all those files, Run all Magento Commands:

php bin/magento set:upg

php bin/magento set:d:c

php bin/magento set:s:d -f en_US

php bin/magento c:c

php bin/magento c:f

New, button will be added on Sales order view page. 
On click on that button one modal window will open with form and after submit the form you can do your custom work as per define in Controller/Adminhtml/Order/Order.php file.




0 Comments On "Magento2 Add New Button on Sales Order View Page and Submit Form for your custom task. "

Back To Top