Magento – How to filter grid by custom column -magento2

admincustomgridmagento2

I have custom column(testname) in admin grid for custom module Where current table of module is Table A and testname is store in Table C But Table B joins both tables.I have displayed value in the grid with join as Below :

<column name="testname" class="Vendor\Namespace\Ui\Component\Listing\Column\TestName">
    <argument name="data" xsi:type="array">                
        <item name="config" xsi:type="array">
            <item name="filter" xsi:type="string">select</item>
            <item name="dataType" xsi:type="string">text</item>
            <item name="sortable" xsi:type="boolean">false</item>
            <item name="label" xsi:type="string" translate="true">TestName</item>
        </item>
    </argument>
</column>

public function prepareDataSource(array $dataSource) 
{ 
    foreach ($dataSource['data']['items'] as & $item) 
    {      
        $groupsarr=array();
        $resultPage = $this->_modelItemsFactory->create();
        $collection = $resultPage->getCollection(); 
        $Collection1 = $collection->addTableC()->addTableB($item['tablea_id']);

        foreach($Collection1 as $TestName)
        {
            $groupsarr[]=$TestName->getName(); 
            $item['testname']= implode(', ', $groupsarr); 
        }
    }

    return $dataSource;
}

It works perfect and showing the column name but how can i add those values in filter and how to filter result with this column?

Best Answer

I have found solution as below : To add custom filtration, I have created method _renderFiltersBefore and written join sql query in /Model/Resource/Items/collection as below :

protected function _renderFiltersBefore()
    {
        $this->getSelect()->join(......);
        return parent::_renderFiltersBefore();
    }

but there was some issue with alias in sql so I have added : $this->addFilterToMap('entity_id', 'main_table.entity_id'); Now it works perfectly.