How To Add Mass Actions In Magento 2

Steps to add Mass Actions in Magento 2

Create Adminhtml Layout File

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

Insert A MassAction Tag In UI Component Xml File

Directory

app/code/VendorName/ModuleName/view/adminhtml/ui_component/modulename_examplerate_listing.xml

Content for modulename_examplerate_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">VendorName\ModuleName\Ui\Component\MassAction\Status\Options</argument>
           <argument name="data" xsi:type="array">
               <item name="urlPath" xsi:type="string">modulename/examplerate/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">VendorName\ModuleName\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>

Add Options To Select

Directory

app/code/VendorName/ModuleName/Ui/Component/MassAction/Status/Options.php

Content for Options.php

namespace VendorName\ModuleName\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;
           }
       }
   }
}

 

Create Controller File

Directory

app/code/VendorName/ModuleName/Controller/Adminhtml/ExampleRate/MassStatus.php

Content for MassStatus.php

namespace VendorName\ModuleName\Controller\Adminhtml\ExampleRate;

use Magento\Backend\App\Action\Context;
use VendorName\ModuleName\Model\ResourceModel\Rate\CollectionFactory;
use Magento\Ui\Component\MassAction\Filter;
use Magento\Framework\Controller\ResultFactory;
use VendorName\ModuleName\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('VendorName_ModuleName::Example_Rate');
   }

}

Flush or Clean Cache

To clean cache, run the following command.

php bin/magento cache:clean

If you are looking for Magento Developer, visit Magento Web Agency.

Related Posts
  1. How To Add Configurable Product In Magento 2
  2. Setup Multiple Stores in Magento 2
  3. BENEFITS OF HAVING MAGENTO 2 UX
  4. Benefits of Magento 2 Improved Layered Navigation