:::: MENU ::::

Magento 2 use plugin

Magento 2 use plugin

Today we talk about how in Magento 2 use plugin. The plugin or Interceptor is a class the modify the behaviour of public class method by interceptions. The plugin give use three option to use After methods, Before methods and Around Method. This tutorial included example of how to add button on sales order view page. Now Following this example you can use plugin with any public class method in magento 2. So let start with our example.

Create di.xml

First create the di.xml in QaisarSatti/HelloWorld/etc/di.xml if it is not already created. If it is already create just add the plugin code.

<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="QaisarSatti_HelloWorld::AddButtonOrderView" type="QaisarSatti\HelloWorld\Plugin\AddButtonOrderView" />

Create AddButtonOrderView.php

Now we create AddButtonOrderView.php in following directory QaisarSatti\HelloWorld\Plugin. Inject \Magento\Sales\Block\Adminhtml\Order\View in your method to get block obejct.

namespace QaisarSatti\HelloWorld\Plugin;

class AddButtonOrderView

    public function beforeSetLayout(\Magento\Sales\Block\Adminhtml\Order\View $object)
            $message = __('Are you sure you want to perform this action?');
  $url = $object->getUrl('addurlhere', ['order_id' =>$object->getOrderId()]);
                    'label' => __('Test Buttonl'),
                    'onclick' => "confirmSetLocation('{$message}', '{$url}')"

Note: Following this example you can use plugin with other public class methods too.

Author: Qaisar Satti
Category: Magento 2
Last Modified: July 12, 2018

So, what do you think ?

You must be logged in to post a comment.