6

I have been digging all day trying to figure out a way to enable/disable the plugins of my custom module with system configuration yes/no. Basically, I have a custom module that adds the Company Column to all Admin Order Grids as well as Customer Grids.

I have created the system.xml file to display the options on the backend, including an option to disable the entire module or just certain Order Grids (Order, Invoice, Shipment, etc).

system.xml:

<system>
    <tab id="trucatch" translate="label" sortOrder="500">
        <label><![CDATA[Trucatch]]></label>
    </tab>
    <section id="companycolumn" translate="label" type="text" sortOrder="140" showInDefault="1" showInWebsite="1" showInStore="1">
        <label><![CDATA[Company Column]]></label>
        <tab>trucatch</tab>
        <resource>Trucatch_CompanyColumn::companycolumn</resource>
        <group id="general" translate="label" type="text" sortOrder="10" showInDefault="1" showInWebsite="1" showInStore="1">
            <label>General</label>
            <field id="enabled" translate="label" type="select" sortOrder="1" showInDefault="1" showInWebsite="1" showInStore="1" canRestore="1">
                <label>Enabled</label><source_model>Magento\Config\Model\Config\Source\Yesno</source_model>
                <comment><![CDATA[Enable to allow Company Column on Sales Grids]]></comment>
            </field>
            <field id="order_grid_enabled" translate="label" type="select" sortOrder="10" showInDefault="1" showInWebsite="1" showInStore="1" canRestore="1">
                <label>Show on Order Grid</label><source_model>Magento\Config\Model\Config\Source\Yesno</source_model>
                <comment><![CDATA[]]></comment>
                <depends>
                    <field id="*/*/enabled">1</field>
                </depends>
            </field>

**Additional Information**

            <field id="invoice_grid_enabled" translate="label" type="select" sortOrder="20" showInDefault="1" showInWebsite="1" showInStore="1" canRestore="1">
                <label>Show on Invoice Grid</label>
                <source_model>Magento\Config\Model\Config\Source\Yesno</source_model>
                <comment><![CDATA[]]></comment>
                <depends>
                    <field id="*/*/enabled">1</field>
                </depends>
            </field>

**End Additional Information**

        </group>
    </section>
</system> 

config.xml:

<default>
    <companycolumn>
        <general>
            <enabled>1</enabled>
            <order_grid_enabled>1</order_grid_enabled>

**Additional Information**

            <invoice_grid_enabled>1</invoice_grid_enabled>

**End Additional Information**

        </general>
    </companycolumn>
</default>

di.xml is calling all the plugins.

Sample:

<type name="Magento\Framework\View\Element\UiComponent\DataProvider\CollectionFactory">
    <plugin 
        name="sales_order_additional_columns" 
        type="Trucatch\CompanyColumn\Plugin\AddColumnsSalesOrderGridCollection" 
        sortOrder="100" 
        disabled="false" 
    />

**Additional Information**

    <plugin 
        name="sales_invoice_additional_columns" 
        type="RLTcode\CompanyColumn\Plugin\AddColumnsSalesInvoiceGridCollection" 
        sortOrder="100" 
        disabled="false" 
    />

**End Additional Information**

</type>

I have also created a Helper\Data.php file to check, but I have not been able to associate that with the actual plugin file. Or am I looking in the wrong place and this needs to be implemented in the layout/ui_component files?

Data.php

namespace Trucatch\CompanyColumn\Helper;

use Magento\Framework\App\Helper\AbstractHelper;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Framework\App\Helper\Context
use Magento\Store\Model\ScopeInterface;

class Data extends AbstractHelper
{
/**
 * Config path to enable/disable module
 */
const CONFIG_PATH_GENERAL_ENABLE_MODULE = 'companycolumn/general/enabled';

/**
 * Config path to enable/disable module
 */
const CONFIG_PATH_GENERAL_ORDER_GRID = 'companycolumn/general/order_grid_enabled';


**Additional Information**

/**
 * Config path to enable/disable module
 */
const CONFIG_PATH_GENERAL_INVOICE_GRID = 'companycolumn/general/invoice_grid_enabled';

**End Additional Information**


protected $_scopeConfig;

public function __construct(
    Context $context,
    \Magento\Backend\Model\UrlInterface $backendUrl,
    ScopeConfigInterface $scopeConfig
) {
    parent::__construct($context);
    $this->_backendUrl = $backendUrl;
    $this->_scopeConfig = $scopeConfig;
}

public function isEnabled()
{
    return $this->scopeConfig->getValue(
        self::CONFIG_PATH_GENERAL_ENABLE_MODULE,
        \Magento\Store\Model\ScopeInterface::SCOPE_STORE
    );
}

public function isOrderGridEnabled()
{
    return (bool) $this->getConfigValue(
        self::CONFIG_PATH_GENERAL_ORDER_GRID,
        \Magenot\Store\Model\ScopeInterface::SCOPE_STORE
    );
}


**Additional Information**

public function isInvoiceGridEnabled()
{
    return $this->scopeConfig->getValue(
        self::CONFIG_PATH_GENERAL_INVOICE_GRID,
        \Magento\Store\Model\ScopeInterface::SCOPE_STORE
    );
}

**End Additional Information**

AddColumnsSalesOrderGridCollection.php:

<?php 

namespace Trucatch\CompanyColumn\Plugin;

class AddColumnsSalesOrderGridCollection
{
private $resource;

public function __construct(
    \Magento\Framework\App\ResourceConnection $resource
) {
    $this->resource = $resource;
}

public function aroundGetReport(
    \Magento\Framework\View\Element\UiComponent\DataProvider\CollectionFactory $subject,
    \Closure $proceed,
    $requestName
) {
    $result = $proceed($requestName);
    if ($requestName == 'sales_order_grid_data_source') {
        if ($result instanceof \Magento\Sales\Model\ResourceModel\Order\Grid\Collection) {
            $select = $result->getSelect();
            $select->joinLeft(
                ['soa1' => $this->resource->getTableName('sales_order_address')],
                'main_table.entity_id = soa1.parent_id AND soa1.address_type = "billing"',
                ['billing_company' => 'company']
            );
            $select->joinLeft(
                ['soa2' => $this->resource->getTableName('sales_order_address')],
                'main_table.entity_id = soa2.parent_id AND soa2.address_type = "shipping"',
                ['shipping_company' => 'company']
            );
        }
    }
    return $result;
}
}

** Additional Information **

AddColumnsSalesInvoiceGridCollection.php

<?php 

namespace Trucatch\CompanyColumn\Plugin;

class AddColumnsSalesInvoiceGridCollection
{
private $resource;

public function __construct(
    \Magento\Framework\App\ResourceConnection $resource
) {
    $this->resource = $resource;
}

public function aroundGetReport(

\Magento\Framework\View\Element\UiComponent\DataProvider\CollectionFactory $subject,
    \Closure $proceed,
    $requestName
) {
    $result = $proceed($requestName);
    if ($requestName == 'sales_order_grid_data_source') {
        if ($result instanceof \Magento\Sales\Model\ResourceModel\Order\Grid\Collection) {
            $select = $result->getSelect();
            $select->joinLeft(
                ['soa1' => $this->resource->getTableName('sales_order_address')],
                'main_table.entity_id = soa1.parent_id AND soa1.address_type = "billing"',
                ['billing_company' => 'company']
            );
            $select->joinLeft(
                ['soa2' => $this->resource->getTableName('sales_order_address')],
                'main_table.entity_id = soa2.parent_id AND soa2.address_type = "shipping"',
                ['shipping_company' => 'company']
            );
        }
    }
    return $result;
}
}

** End Additional Information **

And Lastly the sales_order_grid.xml: (Added the solution from @kunj below)

<!-- "sales_order_grid_data_source" -->
<columns name="sales_order_columns">

    <!-- sales_order_address billing_company -->
    <column name="billing_company" class="Trucatch\CompanyColumn\Ui\Component\Listing\Column\Company">
        <argument name="data" xsi:type="array">
            <item name="config" xsi:type="array">
                <item name="label" xsi:type="string" translate="true">Bill-to Company</item>
                <item name="sortOrder" xsi:type="number">4</item>
                <item name="align" xsi:type="string">left</item>
                <item name="filter" xsi:type="string">text</item>
                <item name="visible" xsi:type="boolean">true</item>
            </item>
        </argument>
    </column>

    <!-- sales_order_address shipping_company -->
    <column name="shipping_company" class="Trucatch\CompanyColumn\Ui\Component\Listing\Column\Company">
        <argument name="data" xsi:type="array">
            <item name="config" xsi:type="array">
                <item name="label" xsi:type="string" translate="true">Ship-to Company</item>
                <item name="sortOrder" xsi:type="number">6</item>
                <item name="align" xsi:type="string">left</item>
                <item name="filter" xsi:type="string">text</item>
                <item name="visible" xsi:type="boolean">true</item>
            </item>
        </argument>
    </column>

</columns>

** Additional Information **

sales_order_invoice_grid.xml

<!-- "sales_order_invoice_grid_data_source" -->
<columns name="sales_order_invoice_columns">

    <!-- sales_order_address billing_company -->
    <column name="billing_company" class="Trucatch\CompanyColumn\Ui\Component\Listing\Column\Company2">
        <argument name="data" xsi:type="array">
            <item name="config" xsi:type="array">
                <item name="label" xsi:type="string" translate="true">Bill-to Company</item>
                <item name="sortOrder" xsi:type="number">5</item>
                <item name="align" xsi:type="string">left</item>
                <item name="filter" xsi:type="string">text</item>
                <item name="visible" xsi:type="boolean">true</item>
            </item>
        </argument>
    </column>

    <!-- sales_order_address shipping_company -->
    <column name="shipping_company" class="Trucatch\CompanyColumn\Ui\Component\Listing\Column\Company2">
        <argument name="data" xsi:type="array">
            <item name="config" xsi:type="array">
                <item name="label" xsi:type="string" translate="true">Ship-to Company</item>
                <item name="sortOrder" xsi:type="number">6</item>
                <item name="align" xsi:type="string">left</item>
                <item name="filter" xsi:type="string">text</item>
                <item name="visible" xsi:type="boolean">true</item>
            </item>
        </argument>
    </column>

</columns>

** End Additional Information **

I am looking to be able to enable/disable certains aspects of this module. For instance you could disable the Company Column from the Sales Order Grid (all information associated with that is above). But I can't seem to grasp how to implement it into my plugins, if it is even possible.

I do understand that you can hide columns and such in Magento2 but I thought this would be an easy way to implement it as well. This way it would not load them for Filters also, but I am still working on getting the Filtering to work.

Please let me know if you need anything else to better assist me.

** Additional Information **

I have added the answer provided by @kunj to my post above. Besides the Company.php file which you can see in the answer. As well I have added another bit of information which handles the Company Name on the Invoice Grid.

** End Additional Information **

  • Is there a way to change disabled="false" to disabled="true" in the di.xml with the Yes/No feature from the system.xml? – RLTcode Aug 27 '18 at 13:32
3
+50

Try this, it is working for me :

    <!-- sales_order_address billing_company -->
    <column name="billing_company" class="Trucatch\CompanyColumn\Ui\Component\Listing\Column\Company">
        <argument name="data" xsi:type="array">
            <item name="config" xsi:type="array">
                <item name="label" xsi:type="string" translate="true">Bill-to Company</item>
                <item name="sortOrder" xsi:type="number">4</item>
                <item name="align" xsi:type="string">left</item>
                <item name="filter" xsi:type="string">text</item>
                <item name="visible" xsi:type="boolean">true</item>
            </item>
        </argument>
    </column>

    <!-- sales_order_address shipping_company -->
    <column name="shipping_company"  class="Trucatch\CompanyColumn\Ui\Component\Listing\Column\Company">
        <argument name="data" xsi:type="array">
            <item name="config" xsi:type="array">
                <item name="label" xsi:type="string" translate="true">Ship-to Company</item>
                <item name="sortOrder" xsi:type="number">6</item>
                <item name="align" xsi:type="string">left</item>
                <item name="filter" xsi:type="string">text</item>
                <item name="visible" xsi:type="boolean">true</item>
            </item>
        </argument>
    </column>

</columns>

Now we need to disable component based on our configuration in Company.php

<?php
/**
 * Created by PhpStorm.
 * User: Kunj
 */

namespace Trucatch\CompanyColumn\Ui\Component\Listing\Column;


class Company  extends \Magento\Ui\Component\Listing\Columns\Column
{
    /**
     * constructor
     *
     * @param \Trucatch\CompanyColumn\Helper\Data $configData
     * @param \Magento\Framework\View\Element\UiComponent\ContextInterface $context
     * @param \Magento\Framework\View\Element\UiComponentFactory $uiComponentFactory
     * @param array $components
     * @param array $data
     */
    private $configData;

    public function __construct(
        \Trucatch\CompanyColumn\Helper\Data $configData,
        \Magento\Framework\View\Element\UiComponent\ContextInterface $context,
        \Magento\Framework\View\Element\UiComponentFactory $uiComponentFactory,
        array $components = [],
        array $data = []
    )
    {
        $this->configData = $configData;
        parent::__construct($context, $uiComponentFactory, $components, $data);
    }

    public function prepare()
    {
        $config = $this->getData('config');
        $myData = ((!$this->configData->isOrderGridEnabled()))?['visible' => "0",'componentDisabled'=>"1"]:['visible' => "1",'componentDisabled'=>"0"];
        foreach ($myData as $field => $value)
        {
            $config[$field] = (bool)$value;
        }
        $this->setData('config', (array)$config);
        parent::prepare();
    }

}

Above code will remove field if set NO in configuration and below code will display field but with the blank value.

<?php
/**
 * Created by PhpStorm.
 * User: kunj
 */

namespace Mageplaza\HelloWorld\Plugin;


class AddColumnsSalesOrderGridCollection
{
    private $resource;

    private $data;

    public function __construct(
        \Magento\Framework\App\ResourceConnection $resource,
        \Mageplaza\HelloWorld\Helper\Data $data
    ) {
        $this->data = $data;
        $this->resource = $resource;
    }

    public function aroundGetReport(
        \Magento\Framework\View\Element\UiComponent\DataProvider\CollectionFactory $subject,
        \Closure $proceed,
        $requestName
    ) {
        $result = $proceed($requestName);
        if (($requestName == 'sales_order_grid_data_source') &&($this->data->isOrderGridEnabled())) {
            if ($result instanceof \Magento\Sales\Model\ResourceModel\Order\Grid\Collection) {
                $select = $result->getSelect();
                $select->joinLeft(
                    ['soa1' => $this->resource->getTableName('sales_order_address')],
                    'main_table.entity_id = soa1.parent_id AND soa1.address_type = "billing"',
                    ['billing_company' => 'company']
                );
                $select->joinLeft(
                    ['soa2' => $this->resource->getTableName('sales_order_address')],
                    'main_table.entity_id = soa2.parent_id AND soa2.address_type = "shipping"',
                    ['shipping_company' => 'company']
                );
            }
        }
        return $result;
    }
}
  • Excellent Option 1 is working perfectly! Thank you. I did have to make a slight change in my Data.php file in order for this to work as I was receiving a few errors but now it's good to go! Can you please advise how to incorporate the isEnabled() as well? Currently it is just hiding all other fields in admin. I have multiple other functions in my Data.php that I need to incorporate as well isInvoiceGridEnabled(). – RLTcode Aug 29 '18 at 14:39
  • Welcome!, happy to help, please elaborate about method query? – kunj Aug 29 '18 at 16:17
  • if isEnabled() is disabled all others functions for the module are disabled. Additional functions in Data.php are isInvoiceGridEnabled(), isShipmentGridEnabled(), and about 10 others which display the column in all admin grids. So I would need an array in Company.php to possibly check all functions in Data.php rather than just isOrderGridEnabled. Not sure if that answers your request. Thanks! – RLTcode Aug 29 '18 at 16:38
  • if you want to display same filed in the different grid then you can add all method condition in the same place. I would suggest you make each file for each grid. – kunj Aug 30 '18 at 5:44
  • 1
    Nevermind, I just created additional Ui Component files and it is working fine. I had to make an adjustment in Data.php in order for isEnabled() to cancel all others if turned off. The only thing I am stuck on now is how to use the system config setting to hide the column in Customer -> Orders Tab Grid. I add the column by extending Block/Adminhtml/Edit/Tab/Orders.php but I can't figure out how to check the Data.php file and then send a forwardNoRoute possibly? – RLTcode Sep 13 '18 at 21:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.