5

Added custom columns from custom table to Customers grid using JOIN in the following method:

\Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection::_beforeLoad: 
protected function _beforeLoad()
{
    ...
    $this->_eventManager->dispatch('core_collection_abstract_load_before', ['collection' => $this]);
    ...
}

and by subscribing to the following event:

 
core_collection_abstract_load_before 

To make custom columns to appear in the Customers grid we are using custom

 
view/adminhtml/ui_component/customer_listing.xml 

file in our module:

<columns name="customer_columns">
    <column name="prxgtDwnlParentId">
        <argument name="data" xsi:type="array">
            <item name="config" xsi:type="array">
                <item name="filter" xsi:type="string">textRange</item>
                <item name="label" xsi:type="string" translate="true">Parent ID</item>
            </item>
        </argument>
    </column>
    <column name="prxgtDwnlCustomerDepth">
        <argument name="data" xsi:type="array">
            <item name="config" xsi:type="array">
                <item name="filter" xsi:type="string">textRange</item>
                <item name="label" xsi:type="string" translate="true">Depth</item>
            </item>
        </argument>
    </column>
</columns>

Everything is working fine, but since we are using aliases for field names filtering is not working.

We came up with the following dirty hack to make it work, basically through reverse transformation "alias" => "table.field":


public function execute(\Magento\Framework\Event\Observer $observer)
{
    ...
    /* the dirty hack */
    $where = $query->getPart('where');
    $replaced = $this->_replaceAllAliasesInWhere($where);
    $query->setPart('where', $replaced);
    ...
}

protected function _replaceAllAliasesInWhere($where)
{
    $result = [];
    foreach ($where as $item) {
        $item = $this->_replaceAliaseInWhere($item, self::AS_FLD_CUSTOMER_DEPTH, self::AS_TBL_CUST, 'depth');
        $item = $this->_replaceAliaseInWhere($item, self::AS_FLD_PARENT_ID, self::AS_TBL_CUST, 'parent_id');
        $result[] = $item;
    }
    return $result;
}

protected function _replaceAliaseInWhere($where, $fieldAlias, $tableAlias, $fieldName)
{
    $search = "`$fieldAlias`";
    $replace = "`$tableAlias`.`$fieldName`";
    $result = str_replace($search, $replace, $where);
    return $result;
}

There should be much more elegant way of doing it. Please, advise.

Your Answer

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

Browse other questions tagged or ask your own question.