In this article, we are going to discuss about applying condition on the massaction. The following are the steps to implement this.
Step 1: Display Massaction on the content Pages in Magento2
Step 2:Â Apply Condition to Show or Hide Newly Created Massaction
Lets start…
Step 1: Display Massaction on the content Pages in Magento2
Lets assume that you need to display massaction on the Admin – Content Pages.
Create file located at Thecoachsmb/ToggleMassaction/view/adminhtml/ui_component/cms_page_listing.xml
and content will be:-
<?xml version="1.0" encoding="UTF-8"?> <!-- /** * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ --> <listing xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Ui:etc/ui_configuration.xsd">  <listingToolbar name="listing_top">    <massaction name="listing_massaction" class="Thecoachsmb\ToggleMassaction\Ui\Component\MassAction">      <action name="custommassaction">        <settings>          <confirm>            <message translate="true">Are you sure to perform Action for selected customers?</message>            <title translate="true">Custom MassAction</title>          </confirm>          <url path="extension/controller/massAction"/> <!-- your custom controller to handle request -->          <type>custommassaction</type>          <label translate="true">Custom MassAction</label>        </settings>      </action>    </massaction>  </listingToolbar> </listing>
Step 2:Â Apply Condition to Show or Hide Newly Created Massaction
Create file at
Thecoachsmb\ToggleMassaction\Ui\Component\MassAction.php
and content will be :
<?php
namespace Thecoachsmb\ToggleMassaction\Ui\Component;
use Magento\Contact\Helper\Data;
class MassAction extends \Magento\Ui\Component\MassAction
{
 /**
  * @param \Magento\Framework\App\Helper\Context $context
  * @param \Magento\Customer\Model\Session $customerSession
  * @param CustomerViewHelper $customerViewHelper
  */
  public function __construct(
   \Magento\Framework\App\Helper\Context $context,
   Data $contacthelper
 ) {
   $this->contacthelper = $contacthelper;
   parent::__construct($context);
 }
  public function prepare()
 {
   parent::prepare();
   $result = $this->contacthelper->isEnabled();
   if ($result == 0) {
     $config = $this->getConfiguration();
     $notAllowedActions = ['custommassaction'];
     $allowedActions = [];
     foreach ($config['actions'] as $action) {
       if (!in_array($action['type'], $notAllowedActions)) {
         $allowedActions[] = $action;
       }
     }
     $config['actions'] = $allowedActions;
     $this->setData('config', (array)$config);
   }
 }
}
We have applied the condition that the if the contact us module is enabled then show this massaction.
