How To Add Mass Actions In Magento 2

In the previous lesson, I showed you How To Custom Admin Grid In Magento 2. Following that lesson, I will show you How To Add Mass Actions In Magento 2.

This is a series on Magento 2 Extension Tutorial. The lessons are related to each other so you should read the previous lessons to be able to do this lesson.

Module File Structure

We updated our module file structure looks as follows:

add mass actions folder Structure

Custom display status

As you know we have displayed status in the admin grid but status only has value is 1 or 0, it is not clear. We will to show Enable or Disable text and change text box to select option in header filter.

Replace the status column code in helloworld_posts_grid_block.xml according to the path: Magetop/Helloworld/view/adminhtml/layout/helloworld_posts_grid_block.xml.

old status column code

Replace by code:

<block class="Magento\Backend\Block\Widget\Grid\Column" as="status">
                        <arguments>
                            <argument name="header" xsi:type="string" translate="true">Status</argument>
                            <argument name="index" xsi:type="string">status</argument>
                            <argument name="type" xsi:type="string">options</argument>
                            <argument name="options" xsi:type="options" model="Magetop\Helloworld\Model\System\Config\Status"/>
                        </arguments>
                    </block>

Create Status.php in Magetop/Helloworld/Model/System/Config/Status.php

<?php
namespace Magetop\Helloworld\Model\System\Config;

use Magento\Framework\Option\ArrayInterface;

class Status implements ArrayInterface
{
    const ENABLED  = 1;
    const DISABLED = 0;

    /**
     * @return array
     */
    public function toOptionArray()
    {
        $options = [
            self::ENABLED => __('Enabled'),
            self::DISABLED => __('Disabled'),
        ];
        return $options;
    }

}

You can see that the status column is showing Enable and Disable now.

change status column

Add Mass Actions

Add Mass Status

Change status Action help admin can change multi-status in Grid. you can select items in the checkbox and click change action.

You need to create MassStatus.php in Magetop/Helloworld/Controller/Adminhtml/Posts/MassStatus.php.

<?php
namespace Magetop\Helloworld\Controller\Adminhtml\Posts;

use Magetop\Helloworld\Controller\Adminhtml\Posts;
use Magento\Backend\App\Action\Context;
use Magento\Framework\Registry;
use Magento\Framework\View\Result\PageFactory;
use Magetop\Helloworld\Model\PostsFactory;
use Magetop\Helloworld\Model\ResourceModel\PostsFactory as resPostsFactory;

class MassStatus extends Posts
{
    protected $_resPostsFactory;

    public function __construct(
        Context $context,
        Registry $coreRegistry,
        PageFactory $resultPageFactory,
        PostsFactory $postsFactory,
        resPostsFactory $resPostsFactory
    )
    {
        parent::__construct($context, $coreRegistry, $resultPageFactory, $postsFactory);
        $this->_resPostsFactory = $resPostsFactory;
    }

    public function execute()
    {
        $status = $this->getRequest()->getParam('status', 0);
        $postIds = $this->getRequest()->getParam('posts', array());
        if (count($postIds)) {
            $i = 0;
            foreach ($postIds as $postId) {
                try {
                    $postId = (int)$postId;
                    $model = $this->_postsFactory->create();
                    $resModel = $this->_resPostsFactory->create();
                    $model->setStatus($status)->setId($postId);
                    $resModel->save($model);
                    $i++;

                } catch (\Exception $e) {
                    $this->messageManager->addErrorMessage($e->getMessage());
                }
            }
            if ($i > 0) {
                $this->messageManager->addSuccessMessage(
                    __('A total of %1 item(s) were deleted.', $i)
                );
            }
        } else {
            $this->messageManager->addError(
                __('You can not item, Please check again')
            );
        }
        $this->_redirect('*/*/index');
    }
}

I changed the status of the post with id 4.

Add Mass Delete

Similar to Mass Status, you can also select items in the checkbox and click delete.

You create Mass Delete in Magetop/Helloworld/Controller/Adminhtml/Posts/MassDelete.php.

<?php
namespace Magetop\Helloworld\Controller\Adminhtml\Posts;

use Magetop\Helloworld\Controller\Adminhtml\Posts;
use Magento\Backend\App\Action\Context;
use Magento\Framework\Registry;
use Magento\Framework\View\Result\PageFactory;
use Magetop\Helloworld\Model\PostsFactory;
use Magetop\Helloworld\Model\ResourceModel\PostsFactory as resPostsFactory;

class MassDelete extends Posts
{
    protected $_resPostsFactory;

    public function __construct(
        Context $context,
        Registry $coreRegistry,
        PageFactory $resultPageFactory,
        PostsFactory $postsFactory,
        resPostsFactory $resPostsFactory
    )
    {
        parent::__construct($context, $coreRegistry, $resultPageFactory, $postsFactory);
        $this->_resPostsFactory = $resPostsFactory;
    }

    public function execute()
    {
        $postIds = $this->getRequest()->getParam('posts', array());
        $model = $this->_postsFactory->create();
        $resModel = $this->_resPostsFactory->create();
        if(count($postIds))
        {
            $i = 0;
            foreach ($postIds as $postId) {
                try {
                    $resModel->load($model,$postId);
                    $resModel->delete($model);
                    $i++;
                } catch (\Exception $e) {
                    $this->messageManager->addErrorMessage($e->getMessage());
                }
            }
            if ($i > 0) {
                $this->messageManager->addSuccessMessage(
                    __('A total of %1 item(s) were deleted.', $i)
                );
            }
        }
        else
        {
            $this->messageManager->addErrorMessage(
                __('You can not delete item(s), Please check again %1')
            );
        }
        $this->_redirect('*/*/index');
    }
}

delete blog in admin grid

You can see I deleted the post with id 4.

I hope through this series you can create your own complete module. Good luck!

In addition to How To Add Mass Actions In Magento 2, you can read the articles Admin Grid CRUD In Magento 2.

Follow us for the more helpful article!

We hope this is a useful series for you.

Thank you for reading!

5 4 votes
Article Rating

Aaron LX

Aaron is a passionate writer, crazy about shopping, eCommerce and trends. Besides his outstanding research skills and a positive mind, Aaron eagerly shares his experience with the readers.

Leave a Reply or put your Question here

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x