{"id":1748,"date":"2021-05-03T12:27:41","date_gmt":"2021-05-03T12:27:41","guid":{"rendered":"https:\/\/meetanshi.com\/blog\/add-dynamic-mass-action-in-admin-grid-in-magento-2\/"},"modified":"2025-05-23T09:45:07","modified_gmt":"2025-05-23T04:15:07","slug":"add-dynamic-mass-action-in-admin-grid-in-magento-2","status":"publish","type":"post","link":"https:\/\/meetanshi.com\/blog\/add-dynamic-mass-action-in-admin-grid-in-magento-2\/","title":{"rendered":"How to Add Dynamic Mass Action in Admin Grid in Magento 2"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\">The&nbsp;<a href=\"https:\/\/developer.adobe.com\/commerce\/frontend-core\/ui-components\/\" target=\"_blank\" rel=\"noreferrer noopener\">Mass Actions<\/a>&nbsp;component allows performing specific actions with multiple selected items. Admin can perform a mass operation on the selected items quickly. It saves the admin from the tedious process of completing an operation on a one-by-one record.&nbsp;<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Having a grid in Magento 2 means loads of records maintained in that admin grid, and need often arrives to perform mass action on the various records. No individual or separate record operation is required if the admin grid has a mass action facility. In addition, the admin grid provides the flexibility to&nbsp;<a href=\"https:\/\/meetanshi.com\/blog\/remove-column-from-admin-grid-dynamically-in-magento-2\/\">remove columns from admin grid dynamically<\/a>&nbsp;from the table, allowing for a more tailored and efficient view of the data.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Magento 2 comes with a UI component that assists store admins in adding more items such as columns, filter argument, paging, mass action, etc., for the admin grid.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Earlier, I did post a solution to&nbsp;<a href=\"https:\/\/meetanshi.com\/blog\/add-custom-mass-action-in-order-grid-in-magento-2\/\" target=\"_blank\" rel=\"noreferrer noopener\">add custom mass action in order grid in Magento 2<\/a>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">However, sometimes you may have to dynamically add mass action in the admin grid according to your requirements. For example you can&nbsp;<a href=\"https:\/\/meetanshi.com\/blog\/dynamically-add-link-to-customer-account-navigation-in-magento-2\/\">dynamically add link to customer account navigation in Magento 2<\/a>&nbsp;allows you to customize and enhance the customer\u2019s account dashboard by adding custom links or sections based on specific business needs and requirements.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">For instance, the admin grid has a column named \u2018status\u2019 with three records- pending, confirmed, and unconfirmed. Now admin wants to change all the unconfirmed status with confirmed one and pending status with confirmed. Also, if a new status \u201ccancelled\u201d is created, the cancel status must be available as an option dynamically while using this custom mass action.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Or, if you are using the custom mass action to upgrade the customer group of your selected customers from the grid and you create a custom customer group, using the below solution to\u00a0add dynamic mass action in admin grid in Magento 2, your custom group will be available as an option dynamically!\u00a0<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Method to Add Dynamic Mass Action in Admin Grid in Magento 2<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">1. Use the below code in the&nbsp;<strong>data_listing.xml&nbsp;<\/strong>at&nbsp;<strong><strong>Vendor\/Extension\/view\/adminhtml\/ui_component<\/strong><\/strong><\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">&lt;massaction name=\"listing_massaction\">\n    &lt;argument name=\"data\" xsi:type=\"array\">\n        &lt;item name=\"config\" xsi:type=\"array\">\n            &lt;item name=\"component\" xsi:type=\"string\">Magento_Ui\/js\/grid\/tree-massactions&lt;\/item>\n            &lt;item name=\"indexField\" xsi:type=\"string\">id&lt;\/item>\n        &lt;\/item>\n    &lt;\/argument>\n    &lt;action name=\"change_status\">\n        &lt;settings>\n            &lt;type>change_status&lt;\/type>\n            &lt;label translate=\"true\">Change Status&lt;\/label>\n            &lt;actions class=\"Vendore\\Extension\\Ui\\Component\\MassAction\\Status\\Options\"\/>\n        &lt;\/settings>\n    &lt;\/action>\n&lt;\/massaction><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">2. Use the below code in the<strong>&nbsp;di.xml<\/strong>&nbsp;file at&nbsp;<strong><strong>Vendor\/Extension\/etc<\/strong><\/strong><\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">&lt;type name=\"Vendore\\Extension\\Ui\\Component\\MassAction\\Status\\Options\">\n    &lt;arguments>\n        &lt;argument name=\"data\" xsi:type=\"array\">\n            &lt;item name=\"urlPath\" xsi:type=\"string\">extenssion\/index\/masschangestatus&lt;\/item>\n            &lt;item name=\"paramName\" xsi:type=\"string\">status&lt;\/item>\n            &lt;item name=\"confirm\" xsi:type=\"array\">\n                &lt;item name=\"title\" xsi:type=\"string\" translatable=\"true\">Change Status&lt;\/item>\n                &lt;item name=\"message\" xsi:type=\"string\" translatable=\"true\">Are you sure to change?&lt;\/item>\n            &lt;\/item>\n        &lt;\/argument>\n    &lt;\/arguments>\n&lt;\/type><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">3. Paste the below code in the&nbsp;<strong>Options.php<\/strong>&nbsp;file at&nbsp;<strong><strong>Vendor\/Extension\/UI\/Component\/MassAction\/Status<\/strong><\/strong><\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">&lt;?php\n\nnamespace Vendore\\Extension\\Ui\\Component\\MassAction\\Status;\n\nuse Magento\\Framework\\Phrase;\nuse Magento\\Framework\\UrlInterface;\n\nclass Options implements \\JsonSerializable\n{\n    protected $options;\n    protected $data;\n    protected $urlBuilder;\n    protected $urlPath;\n    protected $paramName;\n    protected $additionalData = [];\n\n    public function __construct(\n        UrlInterface $urlBuilder,\n        array $data = []\n    )\n    {\n        $this->data = $data;\n        $this->urlBuilder = $urlBuilder;\n    }\n\n    public function jsonSerialize()\n    {\n        if ($this->options === null) {\n            $options = [[\n                'value' => 'pending',\n                'label' => 'Pending approval'\n            ], [\n                'value' => 'active',\n                'label' => 'Active'\n            ], [\n                'value' => 'inactive',\n                'label' => 'Inactive'\n            ]];\n            $this->prepareData();\n            foreach ($options as $optionCode) {\n                $this->options[$optionCode['value']] = [\n                    'type' => 'change_status_' . $optionCode['value'],\n                    'label' => __($optionCode['label']),\n                    '__disableTmpl' => true\n                ];\n\n                if ($this->urlPath &amp;&amp; $this->paramName) {\n                    $this->options[$optionCode['value']]['url'] = $this->urlBuilder->getUrl(\n                        $this->urlPath,\n                        [$this->paramName => $optionCode['value']]\n                    );\n                }\n\n                $this->options[$optionCode['value']] = array_merge_recursive(\n                    $this->options[$optionCode['value']],\n                    $this->additionalData\n                );\n            }\n\n            $this->options = array_values($this->options);\n        }\n\n        return $this->options;\n    }\n\n    protected function prepareData()\n    {\n        foreach ($this->data as $key => $value) {\n            switch ($key) {\n                case 'urlPath':\n                    $this->urlPath = $value;\n                    break;\n                case 'paramName':\n                    $this->paramName = $value;\n                    break;\n                case 'confirm':\n                    foreach ($value as $messageName => $message) {\n                        $this->additionalData[$key][$messageName] = (string)new Phrase($message);\n                    }\n                    break;\n                default:\n                    $this->additionalData[$key] = $value;\n                    break;\n            }\n        }\n    }\n}<\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">4. Use the below code in&nbsp;<strong>MassChangeStatus.php&nbsp;<\/strong>file at&nbsp;<strong><strong>Vendor\/Extension\/Controller\/Adminhtml\/Index<\/strong><\/strong><\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">&lt;?php\n\nnamespace Vendore\\Extension\\Controller\\Adminhtml\\Index;\n\nuse Magento\\Backend\\App\\Action;\nuse Magento\\Backend\\App\\Action\\Context;\nuse Magento\\Framework\\Controller\\ResultFactory;\nuse Magento\\Framework\\View\\Result\\PageFactory;\nuse Magento\\Ui\\Component\\MassAction\\Filter;\nuse Vendore\\Extension\\Model\\ExtensionModelFactory;\nuse Vendore\\Extension\\Model\\ResourceModel\\ExtensionModel\\CollectionFactory;\n\n;\n\nclass MassChangeStatus extends Action\n{\n    protected $filter;\n    protected $resultPageFactory;\n    protected $collectionFactory;\n    protected $extensionModelFactory;\n    private $scopeConfig;\n\n    public function __construct(\n        Context $context,\n        PageFactory $resultPageFactory,\n        Filter $filter,\n        ScopeConfigInterface $scopeConfig,\n        ExtensionModelFactory $extensionModelFactory,\n        CollectionFactory $collectionFactory\n    )\n    {\n        parent::__construct($context, $resultPageFactory);\n        $this->resultPageFactory = $resultPageFactory;\n        $this->filter = $filter;\n        $this->scopeConfig = $scopeConfig;\n        $this->extensionModelFactory = $extensionModelFactory;\n        $this->collectionFactory = $collectionFactory;\n    }\n\n    public function execute()\n    {\n        try {\n            $collection = $this->filter->getCollection($this->collectionFactory->create());\n            $updated = 0;\n            foreach ($collection as $item) {\n                $model = $this->extensionModelFactory->create()->load($item['id']);\n                $model->setData('status', $this->getRequest()->getParam('status'));\n                $model->save();\n                $updated++;\n            }\n            if ($updated) {\n                $this->messageManager->addSuccess(__('A total of %1 record(s) were updated.', $updated));\n            }\n\n        } catch (\\Exception $e) {\n            \\Magento\\Framework\\App\\ObjectManager::getInstance()->get('Psr\\Log\\LoggerInterface')->info($e->getMessage());\n        }\n        $resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT);\n        $resultRedirect->setUrl($this->_redirect->getRefererUrl());\n        return $resultRedirect;\n    }\n\n    protected function _isAllowed()\n    {\n        return true;\n    }\n}<\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">After applying the above method, the mass action displays in the admin grid as shown below:<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img decoding=\"async\" src=\"https:\/\/meetanshi.com\/blog\/wp-content\/uploads\/2021\/04\/Screenshot-at-March-17th-2021-10.00.02-am.png\" alt=\"How to Add Dynamic Mass Action in Admin Grid in Magento 2\" class=\"wp-image-14597\"\/><\/figure>\n<\/div>\n\n\n<p class=\"wp-block-paragraph\">Quite lengthy but worth applying. Right?<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Do consider sharing this post with Magento Community via social media.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Thank you.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>The&nbsp;Mass Actions&nbsp;component allows performing specific actions with multiple selected items. Admin can perform a mass operation on the selected items quickly. It saves the admin&#8230;<\/p>\n","protected":false},"author":5,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"footnotes":""},"categories":[34],"tags":[],"class_list":["post-1748","post","type-post","status-publish","format-standard","hentry","category-magento"],"acf":[],"_links":{"self":[{"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/posts\/1748","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/users\/5"}],"replies":[{"embeddable":true,"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/comments?post=1748"}],"version-history":[{"count":5,"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/posts\/1748\/revisions"}],"predecessor-version":[{"id":15698,"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/posts\/1748\/revisions\/15698"}],"wp:attachment":[{"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/media?parent=1748"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/categories?post=1748"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/meetanshi.com\/blog\/wp-json\/wp\/v2\/tags?post=1748"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}