Adding a Custom Button to Magento2 Admin Product Edit Page
Hello developers! Today we’re going to tackle an important task: adding a custom button next to the page action buttons (Back, Save) on the admin product edit page in Magento2.
Understanding the Adminhtml Module
Before we dive into the code, let’s quickly recap the structure of the adminhtml module where these actions are located. You can find it under app/code/Magento/Adminhtml.
The adminhtml module is responsible for handling all the backend operations and displays. It contains controllers, views, layouts, and templates for the admin panel.
Extending the Adminhtml Layout
To add a new button next to the page action buttons, we need to extend the layout of the product edit form (adminhtml_product_edit_index.xml).
- Navigate to your custom module configuration file under
app/code/Vendor/Module/etc/adminhtml. If you don’t have it, create an XML file named after your controller.
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Config/etc/config.xsd">
<menu>
<!-- Define your menu -->
</menu>
<acl>
<!-- Define ACL rules -->
</acl>
<layout>
<updates>
<Vendor_Module module="Vendor_Module">
<layout file="adminhtml_product_edit_index.xml"/>
</Vendor_Module>
</updates>
</layout>
</config>
- Now create the
adminhtml_product_edit_index.xmllayout file in your module’s view directory:app/code/Vendor/Module/view/adminhtml/layout.
Adding the Custom Button
In this XML layout file, we’ll add a new reference to our custom button.
<!-- The <referenceBlock> will place our block after the page.actions -->
<block class="Magento\Backend\Block\Widget\Button" name="custom_button">
<arguments>
<!-- Specify the button label and action -->
<argument name="label" translate="true">Custom Action</argument>
<argument name="class" translate="html">action-primary</argument>
<argument name="on_click" xsi:type="string">javascript:alert('Custom Action clicked!')</argument>
</arguments>
</block>
<!-- Add the button after the page.actions -->
<referenceBlock name="page.actions">
< block class="Magento\Backend\Block\Widget\Button" name="custom_button"/>
</referenceBlock>
Here, we’re using the Magento\Backend\Block\Widget\Button block to create our custom button. We specify the label (“Custom Action”), CSS class (for styling), and an on-click JavaScript function that will trigger when the button is clicked.
The Final Touches
Make sure you’ve cleared your cache (bin/magento cache:clean) and refresh your admin panel. You should now see a shiny new “Custom Action” button right next to the Save and Back buttons on the product edit page!
Remember, this is a basic example. In a real-world scenario, your custom action would likely involve calling a controller method or performing some complex operation.
For more advanced customizations and layout manipulation in Magento2, check out our detailed guide on Extending Magento2 Layouts.
Happy coding!