Five Steps To Add Mass Actions In Magento 2

Magento 2 comes with UI component which assists store admins in adding more items such as column, filter argument, paging, mass action, etc. for admin grid. If you are looking for a simple way to add mass action in admin grid in Magento 2, this post is here to help you! Specifically, I will show you how to add change status mass action to custom admin grid. Let’s explore five below steps!

Step 1: Create Adminhtml Layout File

Here you can see the Adminhtml layout file:

<body>
   <referenceContainer name="content">
       <uiComponent name="rewardpoints_earningrates_listing"/>
   </referenceContainer>
</body>

Step 2: Insert A MassAction Tag In UI Component Xml File

In this step, you need to insert a massAction tag in UI component xml file: app/code/Mageplaza/Rewardpoints/view/adminhtml/ui_component/rewardpoints_earningrates_listing.xml

<massaction name="listing_massaction">
   <action name="change_status">
       <argument name="data" xsi:type="array">
           <item name="config" xsi:type="array">
               <item name="type" xsi:type="string">change_status</item>
               <item name="label" xsi:type="string" translate="true">Change status</item>
           </item>
       </argument>
       <argument name="actions" xsi:type="configurableObject">
           <argument name="class" xsi:type="string">Mageplaza\Rewardpoints\Ui\Component\MassAction\Status\Options</argument>
           <argument name="data" xsi:type="array">
               <item name="urlPath" xsi:type="string">rewardpoints/earningrates/massStatus</item>
               <item name="paramName" xsi:type="string">status</item>
           </argument>
       </argument>
   </action>
</massaction>
<columns>
 <column name="status">
    <argument name="data" xsi:type="array">
       <item name="options" xsi:type="object">Mageplaza\Rewardpoints\Ui\Component\Listing\Column\Status</item>
       <item name="config" xsi:type="array">
           <item name="editor" xsi:type="string">select</item>
           <item name="filter" xsi:type="string">select</item>
           <item name="component" xsi:type="string">Magento_Ui/js/grid/columns/select</item>
           <item name="dataType" xsi:type="string">select</item>
           <item name="label" xsi:type="string" translate="true">Status</item>
       </item>
    </argument>
  </column>
</columns>

Step 3: Add Options To Select

Then, please add options to select:

app/code/Mageplaza/Rewardpoints/Ui/Component/MassAction/Status/Options.php

namespace Mageplaza\Rewardpoints\Ui\Component\MassAction\Status;

use Magento\Framework\UrlInterface;
use Zend\Stdlib\JsonSerializable;

/**
* Class Options
*/
class Options implements JsonSerializable
{
   /**
    * @var array
    */
   protected $options;

   /**
    * Additional options params
    *
    * @var array
    */
   protected $data;

   /**
    * @var UrlInterface
    */
   protected $urlBuilder;

   /**
    * Base URL for subactions
    *
    * @var string
    */
   protected $urlPath;

   /**
    * Param name for subactions
    *
    * @var string
    */
   protected $paramName;

   /**
    * Additional params for subactions
    *
    * @var array
    */
   protected $additionalData = [];

   /**
    * Constructor
    *
    * @param CollectionFactory $collectionFactory
    * @param UrlInterface $urlBuilder
    * @param array $data
    */
   public function __construct(
       UrlInterface $urlBuilder,
       array $data = []
   ) {
       $this->data = $data;
       $this->urlBuilder = $urlBuilder;
   }

   /**
    * Get action options
    *
    * @return array
    */
   public function jsonSerialize()
   {
       if ($this->options === null) {
           $options = array(
               array(
                   "value" => "1",
                   "label" => ('Active'),
               ),
               array(
                   "value" => "2",
                   "label" => ('Inactive'),
               )
           );
           $this->prepareData();
           foreach ($options as $optionCode) {
               $this->options[$optionCode['value']] = [
                   'type' => 'status_' . $optionCode['value'],
                   'label' => $optionCode['label'],
               ];

               if ($this->urlPath && $this->paramName) {
                   $this->options[$optionCode['value']]['url'] = $this->urlBuilder->getUrl(
                       $this->urlPath,
                       [$this->paramName => $optionCode['value']]
                   );
               }

               $this->options[$optionCode['value']] = array_merge_recursive(
                   $this->options[$optionCode['value']],
                   $this->additionalData
               );
           }
           $this->options = array_values($this->options);
       }
       return $this->options;
   }

   /**
    * Prepare addition data for subactions
    *
    * @return void
    */
   protected function prepareData()
   {
       foreach ($this->data as $key => $value) {
           switch ($key) {
               case 'urlPath':
                   $this->urlPath = $value;
                   break;
               case 'paramName':
                   $this->paramName = $value;
                   break;
               default:
                   $this->additionalData[$key] = $value;
                   break;
           }
       }
   }
}

Step 4: Create Controller File

Now, it is time for you to create the Controller file: app/code/Mageplaza/Rewardpoints/Controller/Adminhtml/Earningrates/MassStatus.php

namespace Mageplaza\Rewardpoints\Controller\Adminhtml\Earningrates;

use Magento\Backend\App\Action\Context;
use Mageplaza\Rewardpoints\Model\ResourceModel\Rate\CollectionFactory;
use Magento\Ui\Component\MassAction\Filter;
use Magento\Framework\Controller\ResultFactory;
use Mageplaza\Rewardpoints\Model\ResourceModel\Rate\Collection;

/**
* Class MassDelete
*/
class MassStatus extends AbstractMassAction
{
   /**
    * @param Context $context
    * @param Filter $filter
    * @param CollectionFactory $collectionFactory
    */
   public function __construct(
       Context $context,
       Filter $filter,
       CollectionFactory $collectionFactory
   ) {
       parent::__construct($context, $filter, $collectionFactory);
   }

   /**
    * @param AbstractCollection $collection
    * @return \Magento\Backend\Model\View\Result\Redirect
    */
   protected function massAction(Collection $collection)
   {
       $rateChangeStatus = 0;
       foreach ($collection as $rate) {
           $rate->setStatus($this->getRequest()->getParam('status'))->save();
           $rateChangeStatus++;
       }

       if ($rateChangeStatus) {
           $this->messageManager->addSuccess(__('A total of %1 record(s) were updated.', $rateChangeStatus));
       }
       /** @var \Magento\Backend\Model\View\Result\Redirect $resultRedirect */
       $resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT);
       $resultRedirect->setPath($this->getComponentRefererUrl());

       return $resultRedirect;
   }

   /**
    * @return bool
    */
   protected function _isAllowed()
   {
       return $this->_authorization->isAllowed('Mageplaza_Rewardpoints::Earning_Rates');
   }

}

Step 5: Flush Cache & Check Result

Finally, please flush the cache to check the result. Access here to know how to flush cache step by step!

Conclusion

Above are the details instruction for adding mass action in admin grid in Magento 2. I hope this post is helpful for you. If you have any questions or want to discuss this post, feel free to leave a comment below!

Enjoyed the tutorial? Spread it to your friends!