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.
<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.
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.