Magento 2.1 – How to Add Button to Order View

magento-2.1

I want to add a button to the order view called "Print label" and when clicked it will generate and download a text file. So here is the steps I think I should do:

  • Create button: How do pass order id + use urlbuilder to make a link?)
  • Create a controller that genereates the file (I am familiar with making controllers)

I have already added a button (and a controller) to the sales order grid for another purpose but do not know how to add one to the sales order view:

Vendor/Module/etc/adminhtml/di.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Backend:etc/menu.xsd">
    <menu>
        <add id="Vendor_Module::packinglist" title="Packinglist" module="Vendor_Module" parent="Magento_Sales::sales_operation" action="packinglist/packinglist" resource="Vendor_Module::packinglist"/>
    </menu>
</config>

I have tried this guide but I do not know how to make a link and Ithink I rather us above method to add a button.

Best Answer

I've done this using plugins:

Vendor/Module/etc/adminhtml/di.xml

<?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 name="vendor_module_adminhtml_order_view_add_button" type="Vendor\Module\Plugin\Sales\Block\Adminhtml\Order\View" sortOrder="10" />
  </type>
</config>

Vendor/Module/Plugin/Sales/Block/Adminhtml/Order/View.php

<?php
namespace Vendor\Module\Plugin\Sales\Block\Adminhtml\Order;

use Magento\Sales\Block\Adminhtml\Order\View as OrderView;
use Magento\Framework\UrlInterface;
use Magento\Framework\AuthorizationInterface;

class View
{
  /** @var \Magento\Framework\UrlInterface */
  protected $_urlBuilder;

  /** @var \Magento\Framework\AuthorizationInterface */
  protected $_authorization;

  public function __construct(
    UrlInterface $url,
    AuthorizationInterface $authorization
  ) {
    $this->_urlBuilder = $url;
    $this->_authorization = $authorization;
  }

  public function beforeSetLayout(OrderView $view) {
    $url = $this->_urlBuilder->getUrl('route/to/label', ['id' => $view->getOrderId()]);

    $view->addButton(
      'my_new_button',
      [
        'label' => __('My Button'),
        'class' => 'my-button'
      ]
    );
  }
}
Related Topic