Magento 2 and filtered collections
Ok, I found it by myself. Posting here if it helps:
This kind of filter cannot be done at collection level, but only at data provider level.
So, if you have:
<virtualType name="My\Module\Model\ResourceModel\Grid\Items\Collection"
type="Magento\Framework\View\Element\UiComponent\DataProvider\SearchResult">
<arguments>
<argument name="mainTable" xsi:type="string">my_table</argument>
<argument name="resourceModel"
xsi:type="string">My\Module\Model\ResourceModel\Items\Collection</argument>
</arguments>
</virtualType>
You can just point to your custom data provider instead of inheriting from Magento\Framework\View\Element\UiComponent\DataProvider\SearchResult
.
Your XML becomes:
<virtualType name="My\Module\Model\ResourceModel\Grid\Items\Collection"
type="My\Module\Ui\Component\DataProvider\SearchResult\Items">
<arguments>
<argument name="mainTable" xsi:type="string">my_table</argument>
<argument name="resourceModel"
xsi:type="string">My\Module\Model\ResourceModel\Items\Collection</argument>
</arguments>
</virtualType>
Now we are referring to My\Module\Ui\Component\DataProvider\SearchResult\Items
instead of Magento\Framework\View\Element\UiComponent\DataProvider\SearchResult
.
Now we have to create our new class:
<?php
namespace My\Module\Ui\Component\DataProvider\SearchResult;
class Items extends \Magento\Framework\View\Element\UiComponent\DataProvider\SearchResult
{
protected function _initSelect()
{
parent::_initSelect();
$this->addMyCustomFilter();
return $this;
}
public function addMyCustomFilter()
{
$this
->addFieldToFilter('age', ['gteq' => 18])
return $this;
}
}
Hope it helps.