Add custom buttons to the admin product form in Magento 2.

Product form is developed using UI-components. If we need to add a custom button to the admin product form, this can be done in the following ways.

The UI component name for the product form is:

See / adminhtml / ui_component / product_form.xml.

  1. You need to create a file with the same name and path in your module with the following content.
<?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">WebkulCustomButtonBlockAdminhtmlProductCustomButton</item>
       </item>
   </argument>
</form>

2. Then create a class in the file.

Vendor / module / block / admin html / product / custom button.php.

<?php
namespace WebkulCustomButtonBlockAdminhtmlProduct;
class CustomButton extends MagentoCatalogBlockAdminhtmlProductEditButtonGeneric
{
    public function getButtonData()
    {
    	return [
        	'label' => __('Custom Button'),
        	'class' => 'action-secondary',
        	'on_click' => 'alert("Hello Webkul !!")',
        	'sort_order' => 10
    	];
    }
}

Then, just flush the cache and your UI-Component file will merge into the main file and your button will appear among the other buttons.

When we click on this button we set an alert, it will appear.

Custom buttons

It’s just an easy way to add custom buttons to the admin product form.

Check out this blog if you add custom buttons to the admin grid.

Keep learning !!

Write a Comment

Your email address will not be published. Required fields are marked *