Custom Mass Actions for Magento 2 Product Grid

Custom Mass Actions for Magento 2 Product Grid
Mass actions in Magento 2 let admins update multiple products without opening each one individually. This guide shows you how to add custom mass actions to your product listing page.
Table Of Content
Why Mass Actions Matter
Mass actions increase catalog management efficiency by allowing bulk updates to prices, attributes, categories, and product relationships. Default options include delete and status changes, but custom actions expand what you can do.
The dropdown menu shows available mass actions. Select products using filters, pick an action, and execute it across all selected items. This saves hours when managing large catalogs.
Implementation Overview
Adding mass actions requires three components:
- routes.xml - Defines admin routing
- product_listing.xml - Adds the action to the grid
- Controller class - Processes selected products
Step 1: Configure Admin Routes
Create routes.xml
in your module at YourNamespace/YourModule/etc/adminhtml/routes.xml
:
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">
<router id="admin">
<route id="customaction" frontName="customaction">
<module name="YourNamespace_YourModule"/>
</route>
</router>
</config>
The frontName
becomes part of your controller URL path.
Step 2: Add Mass Action to Grid
Create product_listing.xml
at YourNamespace/YourModule/view/adminhtml/ui_component/product_listing.xml
:
<?xml version="1.0" encoding="UTF-8"?>
<listing xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Ui:etc/ui_configuration.xsd">
<listingToolbar name="listing_top">
<massaction name="listing_massaction">
<action name="custom_action">
<settings>
<confirm>
<message translate="true">Process selected products?</message>
<title translate="true">Confirm Action</title>
</confirm>
<url path="customaction/process/execute"/>
<type>custom_action</type>
<label translate="true">Custom Process</label>
</settings>
</action>
</massaction>
</listingToolbar>
</listing>
Key elements:
<confirm>
- Shows confirmation dialog<url>
- Controller path (routename/controllername/actionname)<type>
- Unique identifier<label>
- Text shown in dropdown
Step 3: Build the Controller
Create the controller at YourNamespace/YourModule/Controller/Adminhtml/Process/Execute.php
:
<?php
namespace YourNamespace\YourModule\Controller\Adminhtml\Process;
use Magento\Backend\App\Action\Context;
use Magento\Backend\App\Action;
use Magento\Catalog\Model\ResourceModel\Product\CollectionFactory;
use Magento\Ui\Component\MassAction\Filter;
class Execute extends Action
{
protected $productCollection;
protected $filter;
public function __construct(
Context $context,
CollectionFactory $productCollection,
Filter $filter
) {
$this->productCollection = $productCollection;
$this->filter = $filter;
parent::__construct($context);
}
public function execute()
{
try {
$collection = $this->filter->getCollection(
$this->productCollection->create()
);
if ($collection->getSize() == 0) {
throw new \Magento\Framework\Exception\LocalizedException(
__('No products selected.')
);
}
$count = 0;
foreach ($collection as $product) {
// Your custom logic here
// Example: $product->setCustomAttribute('value');
// $product->save();
$count++;
}
$this->messageManager->addSuccessMessage(
__('Successfully processed %1 product(s).', $count)
);
} catch (\Exception $e) {
$this->messageManager->addErrorMessage(
__('Error: %1', $e->getMessage())
);
}
return $this->resultRedirectFactory->create()->setPath('catalog/product/');
}
}
The Filter class retrieves selected products as a collection, making it easy to iterate and apply operations.
Tip
To enhance your eCommerce store’s performance with Magento, focus on optimizing site speed by utilizing Emmo themes and extensions. These tools are designed for efficiency, ensuring your website loads quickly and provides a smooth user experience. Start leveraging Emmo's powerful solutions today to boost customer satisfaction and drive sales!
Advanced Mass Actions
Dropdown Options with Dynamic Values
Create conditional mass actions by extending UI components with custom classes:
<action name="assign_category">
<settings>
<type>assign_category</type>
<label translate="true">Assign to Category</label>
<actions class="YourNamespace\YourModule\Ui\Component\MassAction\Options"/>
</settings>
</action>
Then build the Options class:
<?php
namespace YourNamespace\YourModule\Ui\Component\MassAction;
use Magento\Framework\UrlInterface;
class Options implements \JsonSerializable
{
protected $urlBuilder;
protected $options;
public function __construct(UrlInterface $urlBuilder)
{
$this->urlBuilder = $urlBuilder;
}
public function jsonSerialize()
{
if ($this->options === null) {
$categories = [
['value' => '1', 'label' => 'Category 1'],
['value' => '2', 'label' => 'Category 2']
];
foreach ($categories as $category) {
$this->options[] = [
'value' => $category['value'],
'label' => $category['label'],
'url' => $this->urlBuilder->getUrl(
'customaction/process/category',
['category_id' => $category['value']]
)
];
}
}
return $this->options;
}
}
Mass Action Comparison
Feature | Details |
---|---|
Action Type | Simple Action, Dynamic Action, Conditional Action |
Configuration | XML only, XML + PHP class, XML + PHP + Logic |
User Options | Single button, Multiple choices, Config-dependent |
Complexity | Low, Medium, High |
Use Cases | Delete, Enable, Assign categories, Feature flags |
Error Handling Best Practices
Always wrap operations in try-catch blocks:
try {
$collection = $this->filter->getCollection($this->productCollection->create());
if ($collection->getSize() == 0) {
throw new \Magento\Framework\Exception\LocalizedException(__('No products found.'));
}
foreach ($collection as $product) {
// Process product
}
$this->messageManager->addSuccessMessage(__('Action completed.'));
} catch (\Magento\Framework\Exception\LocalizedException $e) {
$this->messageManager->addErrorMessage($e->getMessage());
} catch (\Exception $e) {
$this->messageManager->addErrorMessage(__('An error occurred.'));
}
Testing Your Mass Action
- Clear cache: bin/magento cache:clean
- Navigate to Products > Catalog
- Select products using checkboxes
- Open Actions dropdown
- Verify your custom action appears
- Execute and check results
If checkboxes appear at the end of the grid, delete the bookmark from the database: DELETE FROM ui_bookmark WHERE namespace='product_listing
'
Performance Tips
For large product sets:
- Process in batches of 100-500 products
- Use database transactions
- Consider queue/cron for heavy operations
- Add progress indicators for long-running tasks
Optimize collection queries:
$collection = $this->filter->getCollection($this->productCollection->create());
$collection->addAttributeToSelect(['sku', 'name']); // Only needed fields
$collection->setPageSize(100); // Batch processing
// Additional processing can go here
Common Issues
Mass action not appearing:
- Check module is enabled
- Verify XML file location
- Clear generated code:
bin/magento setup:di:compile
Selected IDs not passing:
- Ensure Filter class is injected
- Check
getCollection()
returns valid data
Permission errors:
- Add ACL rules in acl.xml
- Clear admin sessions
Security Considerations
Always validate user permissions in your controller:
protected function _isAllowed()
{
return $this->_authorization->isAllowed('YourNamespace_YourModule::mass_action');
}
Define permissions in etc/acl.xml
:
<resources>
<resource id="Magento_Backend::admin">
<resource id="YourNamespace_YourModule::mass_action" title="Custom Mass Action" sortOrder="10"/>
</resource>
</resources>
Conclusion
Mass actions streamline product management. Start with simple operations like status updates, then build complex workflows. Extensions are available that provide advanced mass action functionality including price updates, attribute copying, and relationship management.
FAQs
What are custom mass actions in Magento 2?
Custom mass actions allow store admins to perform bulk operations on selected products in the product grid, such as updating attributes, changing statuses, or applying special rules, saving time compared to editing items individually.
Why would I create a custom mass action?
Creating a custom mass action lets you automate repetitive tasks, enforce business rules, and provide functionality tailored to your store’s workflow, improving efficiency for administrators.
Where do I define a custom mass action in Magento 2?
Custom mass actions are defined in your module’s etc/acl.xml
for permissions and added via a UI component in the view/adminhtml/ui_component/product_listing.xml
file, specifying the action class and configuration.
Which files are essential to create a custom mass action?
Key files include: ui_component XML
for grid configuration, a PHP action class to handle the bulk logic, and optionally templates or layout files if a custom interface is needed.
How do I register a custom mass action in Magento 2?
Register the action by updating the product grid UI component XML with your new action, defining the PHP handler, then run bin/magento setup:upgrade
and bin/magento cache:flush
to apply changes.
Can I add custom parameters to a mass action?
Yes. You can include custom parameters in your UI component XML, allowing admins to select options or provide inputs that your action class can process dynamically.
How do I handle validation in a custom mass action?
Implement validation logic in your PHP action class to ensure the selected products meet the criteria for the action. You can also return messages to the admin panel if validation fails.
What if my custom mass action is not showing in the grid?
Verify your UI component XML configuration, ensure the ACL permissions are correct, confirm your module is enabled, and clear caches using bin/magento cache:flush
.
Can I restrict a mass action to specific products?
Yes. You can implement conditions in your action class to filter products based on attributes, status, or categories, ensuring the action applies only to eligible items.
What are best practices for maintaining custom mass actions?
Follow Magento coding standards, keep your action logic modular, document parameters clearly, and test after upgrades to ensure compatibility with new Magento versions and third-party modules.