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" />
    </type>
</config>

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()]);
            $object->addButton(
                'UnCancel',
                [
                    'label' => __('Test Buttonl'),
                    'onclick' => "confirmSetLocation('{$message}', '{$url}')"
                ]
            );
   
    }
}

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

Qaisar Satti

Hi, I'm Qaisar Satti! I've been a developer for over 20 years, and now I love sharing what I've learned through tutorials and guides. Whether you're working with Magento, PrestaShop, or WooCommerce, my goal is to make your development journey a bit easier and more fun. When I'm not coding or writing, you can find me exploring new tech trends and hanging out with the amazing developer community. Thanks for stopping by, and happy coding!

Leave a Reply