Milind Daraniya

How to add a custom button in the admin product - Magento 2

Published July 4th, 2023 2 min read

Today, We will learn how to add custom button in admin product using UI Component in Magento 2. Here we will be using Milind as the Vendor name and CustomButton as the name of the module.  You can change this according to your Vendor and Module name.

First create a product_form.xml file in app/code/Milind/CustomButton/view/adminhtml/ui_component directory in Module.

<?xml version="1.0" encoding="UTF-8"?>
<form xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Ui:etc/ui_configuration.xsd">
   <!--For custom button-->
   <argument name="data" xsi:type="array">
       <item name="buttons" xsi:type="array">
           <item name="customButton" xsi:type="string">Milind\CustomButton\Block\Adminhtml\Product\Edit\Button\CustomButton</item>
       </item>
   </argument>
</form>

And Then create CustomButton.php file in app/code/Milind/CustomButton/Block/Adminhtml/Product/Edit/Button directory and add below code.

<?php
namespace Milind\CustomButton\Block\Adminhtml\Product\Edit\Button;

class CustomButton extends \Magento\Catalog\Block\Adminhtml\Product\Edit\Button\Generic
{
	public function getButtonData()
	{
    	return [
        	'label' => __('Custom Button'),
        	'class' => 'action-secondary',
        	'on_click' => 'alert("On Click Event")',
        	'sort_order' => 10
    	];
	}
}

That's It. 

Now you can see the Custom Button on top of the product in Admin.

Thanks.