Programmatically: How to add a custom button to the Magento product grid
Step 1: Create a new module
Create a new directory CustomProductGridButton inside app/code/local/ (or your desired namespace). Inside this directory, create the following files: composer.json
{
"name": "your-namespace/customproductgridbutton",
"description": "Add custom button to product grid",
"version": "1.0.0",
"type": "magento2-module",
"require": {
"php": "^7.2.5",
"magento/framework": "^102.0.4"
}
}
registration.php
\Magento\Framework\Component\ComponentRegistrar::register(
\Magento\Framework\Component\ComponentRegistrar::MODULE,
'CustomProductGridButton',
__DIR__
);
Step 2: Create the button column
In the app/code/local/CustomProductGridButton/view/frontend/etc/di.xml file, add the following code:
/?xml version="1.0"?>
My Custom Button
action
This XML file defines a new column called custom_button with a label and a class of action.
Step 3: Add the button renderer
In the app/code/local/CustomProductGridButton/view/frontend/view/grid/columns/custom_button.php file, add the following code:
namespace CustomProductGridButton\View\Ui\Component\Column;
class CustomButton extends \Magento\Framework\View\Element\UiComponent\ContextInterface
{
protected $renderer;
public function __construct(
ContextInterface $context,
array $data = []
) {
parent::__construct($context, $data);
$this->renderer = $context->getRegistry()->registry('page_layout');
}
public function render()
{
$this->renderer->getLayout()->addHandle('after_body_end');
return '';
}
}
This class extends the ContextInterface and defines a render() method that returns an HTML button element.
Step 4: Register the column
In the app/code/local/CustomProductGridButton/view/frontend/view/grid/columns/default.xml file, add the following code:
/?xml version="1.0"?>
This XML file registers the custom column in the product grid.
Step 5: Clear caches and refresh
Run the following commands in your terminal:
php bin/magento cache:clean
php bin/magento setup:upgrade
php bin/magento setup:static-content:deploy
Now, when you access the product grid, you should see your custom button.
That's it! You've successfully added a custom button to the Magento product grid programmatically.