Blog

MassDelete Action in the Admin Grid Magento2

The MassAction allows us to perform an operation on multiple items of the grid. You may have seen mass actions on the product grid, which allows us to delete multiple product at once.

In this blog we will create some mass actions. First we will create a MassAction to delete multiple blogs at once.

  1. Display Delete in Action Dropdown
  2. Create Controller to perform Mass Delete actions

1. Display Delete in Action Dropdown

We need to edit the ui component file view/adminhtml/ui_component/blogmanager_blog_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">
            <argument name="data" xsi:type="array">
                <item name="data" xsi:type="array">
                <item name="selectProvider" xsi:type="string">article_grid.article_grid.sonal_article_columns.ids</item>
                <item name="displayArea" xsi:type="string">bottom</item>
                <item name="indexField" xsi:type="string">primary_id</item>
                </item>
            </argument>
            <action name="delete">
                <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="type" xsi:type="string">delete</item>
                    <item name="label" xsi:type="string" translate="true">Delete</item>
                    <item name="url" xsi:type="url" path="routeid/controllername/massDelete"/>
                    <item name="confirm" xsi:type="array">
                        <item name="title" xsi:type="string" translate="true">Delete Blogs?</item>
                        <item name="message" xsi:type="string" translate="true">Are you sure you want to delete the selected blogs?</item>
                    </item>
                </item>
                </argument>
            </action>
        </massaction>
        <bookmark name="bookmarks"/>
        <columnsControls name="columns_controls"/>
...............................................
    </listingToolbar>
    <columns name="sonal_article_columns">
        <selectionsColumn name="ids">
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="indexField" xsi:type="string">primary_id</item>
                </item>
            </argument>
        </selectionsColumn>
        <column name="entity_id">
            <settings>
                <filter>textRange</filter>
                <label translate="true">ID</label>
                <resizeDefaultWidth>25</resizeDefaultWidth>
            </settings>
        </column>
        <column name="title">
            <settings>
                <filter>text</filter>
                <label translate="true">Title</label>
            </settings>
        </column>
    </columns>
</listing>

Here we have added selectionsColumn tag inside the columns tag. It will show the checkbox column to select the rows.

And inside the listingToolbar tag we have added massaction tag which will be used to manage the mass-action dropdown. To add the mass-action action, we have used the action tag, where we have specified label, url for the mass-action, confirmation message, etc.

2. Create Controller to perform Mass Delete actions

Now let’s create the action file for the mass-delete url, Controller/Adminhtml/Controllername/MassDelete.php

<?php
namespace Vendor\Module\Controller\Adminhtml\Controllername;

use Magento\Backend\App\Action;
use Magento\Backend\App\Action\Context;
use Magento\Framework\Controller\ResultFactory;
use Magento\Ui\Component\MassAction\Filter;
use Vendor\Module\Model\ResourceModel\Blog\CollectionFactory;

class MassDelete extends Action
{
    public $collectionFactory;

    public $filter;

    public function __construct(
        Context $context,
        Filter $filter,
        CollectionFactory $collectionFactory,
        \Vendor\Module\Model\ArticleFactory $blogFactory
    ) {
        $this->filter = $filter;
        $this->collectionFactory = $collectionFactory;
        $this->blogFactory = $blogFactory;
        parent::__construct($context);
    }

    public function execute()
    {
        try {
            $collection = $this->filter->getCollection($this->collectionFactory->create());

            $count = 0;
            foreach ($collection as $model) {
                $model = $this->blogFactory->create()->load($model->getArticleId());
                $model->delete();
                $count++;
            }
            $this->messageManager->addSuccess(__('A total of %1 blog(s) have been deleted.', $count));
        } catch (\Exception $e) {
            $this->messageManager->addError(__($e->getMessage()));
        }
        return $this->resultFactory->create(ResultFactory::TYPE_REDIRECT)->setPath('*/*/index');
    }

    public function _isAllowed()
    {
        return $this->_authorization->isAllowed('Vendor_Module::delete');
    }
}

Let’s see what’s this line is doing,
$this->filter->getCollection($this->collectionFactory->create());
With $this->collectionFactory->create(), we are getting the whole blogs collection. And we are passing it in getCollection method of mass-action’s filter class. So it will return the collection of all the rows which we selected while performing this action. And we are iterating through each model and deleting them one by one.

There are few other things new here, which are not limited to mass-action.
__(‘A total of %1 blog(s) have been deleted.’, $count) – the %1 will get replaced with $count
Similarly we can pass multiple variables and format string.

->setPath(‘*/*/index’) – here * means replace this component with current value. So it will replace frontName and controllerName with current values which will be blog and manage respectively.

Please ignore _isAllowed method we will discuss about it when we create ACL as mentioned earlier.

Leave a Reply

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

🚀 Let’s Connect on LinkedIn! 🚀

Want to level up your skills and knowledge? 🚀
Follow us on LinkedIn to get:
✅ Expert insights on business growth
✅ Daily tips to sharpen your skills
✅ Exclusive updates from The Coach SMB

Let's grow together!