Cookies setting

Cookies help us enhance your experience on our site by storing information about your preferences and interactions. You can customize your cookie settings by choosing which cookies to allow. Please note that disabling certain cookies might impact the functionality and features of our services, such as personalized content and suggestions. Cookie Policy

Cookie Policy
Essential cookies

These cookies are strictly necessary for the site to work and may not be disabled.

Information
Always enabled
Advertising cookies

Advertising cookies deliver ads relevant to your interests, limit ad frequency, and measure ad effectiveness.

Information
Analytics cookies

Analytics cookies collect information and report website usage statistics without personally identifying individual visitors to Google.

Information
mageplaza.com

Five Steps To Add Mass Actions In Magento 2

Vinh Jacker | 12-18-2024

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 the admin grid. If you are looking for a simple way to add mass action in the 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 the 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

That’s the detailed instruction for adding mass action in the 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!

x
    Jacker

    With over a decade of experience crafting innovative tech solutions for ecommerce businesses built on Magento, Jacker is the mastermind behind our secure and well-functioned extensions. With his expertise in building user-friendly interfaces and robust back-end systems, Mageplaza was able to deliver exceptional Magento solutions and services for over 122K+ customers around the world.



    Related Post

    Website Support
    & Maintenance Services

    Make sure your store is not only in good shape but also thriving with a professional team yet at an affordable price.

    Get Started
    mageplaza services