Tony's Blog

How to Add a Custom Button to Admin Sales Order View in Magento2

Tony's blog image

1. Create a plugin in Company/Module/etc/adminhtml/di.xml

  1. <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
  2. <type name="Magento\Backend\Block\Widget\Button\Toolbar">
  3. <plugin name="Company_Module::pluginBefore" type="Company\Module\Plugin\PluginBefore" />
  4. </type>
  5. </config>

2. Then in Company/Module/Plugin/PluginBefore.php

  1. <?php
  2. namespace Company\Module\Plugin;
  3. class PluginBefore
  4. {
  5. protected $view;
  6. public function __construct(
  7. \Magento\Sales\Block\Adminhtml\Order\View $view
  8. )
  9. {
  10. $this->view = $view;
  11. }
  12. public function beforePushButtons(
  13. \Magento\Backend\Block\Widget\Button\Toolbar\Interceptor $subject,
  14. \Magento\Framework\View\Element\AbstractBlock $context,
  15. \Magento\Backend\Block\Widget\Button\ButtonList $buttonList
  16. ) {
  17. $orderIds = $this->view->getOrderId();
  18. $message = 'Are you sure you want to do this?'.$orderIds;
  19. $this->_request = $context->getRequest();
  20. if($this->_request->getFullActionName() == 'sales_order_view'){
  21. $buttonList->add(
  22. 'mybutton',
  23. [
  24. 'label' => __('Update Log'),
  25. 'onclick' => "confirmSetLocation('{$message}','{}')",
  26. 'class' => 'go'
  27. ],
  28. -1
  29. );
  30. }
  31. }
  32. }

3. Clear Magento cache and run update command

  1. php bin/magento setup:upgrade

4. Finally you will see the button in backened