Default Magento already provides mass action in admin grid. The obvious purpose of this mass action to perform mass operations for selected items in less time. Some of the most popular mass actions in Magento 2 are delete, change status etc. Want to add mass actions in Magento 2 Admin grid? You can easily do this with UI component. Many times you want to add mass actions in Magento 2 sales, customers, orders, products grid. Here, I will be sharing code to add mass actions in Magento 2 admin grid.
Step 1: First, we need to create “YOUR_UI_COMPONENT_NAME.xml” file inside extension the below directory.
app\code\Vendor\Extension\view\adminhtml\ui_component
<?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="delete"> <settings> <confirm> <message translate="true">Are you sure you want to delete selected items?</message> <title translate="true">Delete Items</title> </confirm> <url path="demo/grid/massdelete"/> <type>delete</type> <label translate="true">Delete</label> </settings> </action> </massaction> </listingToolbar> </listing>
Step 2: Lastly, you need to create a “Massdelete.php” file inside extension the below directory.
app\code\Vendor\Extension\Controller\Adminhtml\Grid
<?php namespace Vendor\Extension\Controller\Adminhtml\Grid; use Magento\Backend\App\Action; use Magento\Framework\Controller\ResultFactory; use Vendor\Extension\Model\ResourceModel\YourModel\CollectionFactory; class Massdelete extends Action { protected $collectionFactory; public function __construct( Action\Context $context, CollectionFactory $collectionFactory ) { parent::__construct($context); $this->collectionFactory = $collectionFactory; } public function execute() { $ids = $this->getRequest()->getParam('selected'); if (!is_array($ids) || empty($ids)) { $this->messageManager->addErrorMessage(__('Please select item(s) to delete.')); } else { try { $collection = $this->collectionFactory->create()->addFieldToFilter('entity_id', ['in' => $ids]); foreach ($collection as $item) { $item->delete(); } $this->messageManager->addSuccessMessage(__('A total of %1 record(s) have been deleted.', count($ids))); } catch (\Exception $e) { $this->messageManager->addErrorMessage($e->getMessage()); } } return $this->resultFactory->create(ResultFactory::TYPE_REDIRECT)->setPath('*/*/'); } }
Feel free to share this post and ask your questions in the comments below.