Magento 2 Grid – Working with Filtered Collections

collection;gridmagento2

I have a collection of users and I want to create a backend grid to show only some user depending on a filter.

For example I want to show all the users in my table whith age greater than 18.

I created a new collection and i added my filter to _initSelect method.

...
protected function _initSelect()
{
    parent::_initSelect();
    $this->addUsersFilter();

    return $this;
}
...
public function addUsersFilter()
{
    $this
        ->addFieldToFilter('age', ['gteq' => 18]);

    return $this;
}
...

Bt my grid keeps showing me the whole table content regardless my filter.

Does anyone knows how to filter a grid directly from its source collection?

Best Answer

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.

Related Topic