Magento 2 Display a Modified Collection in Grid Using Ui Component

In Magento 2, if there is any development requirement to add filters to our collection and displaying our admin grid using ui_component, you need to follow the given steps provided in below code snippet:

Lets say we need to display the products whose price is greater than 200. We need to add below code in directory Magemeta/Uicomponent/view/adminhtml/ui_component/test.xml

<dataSource name="test_custom_products_data_source">
    <argument name="dataProvider" xsi:type="configurableObject">
    <argument name="class" xsi:type="string">Magemeta\Uicomponent\Ui\DataProvider\Product\ProductsDataProvider</argument>
    <argument name="name" xsi:type="string">test_products_data_source</argument>
    <argument name="primaryFieldName" xsi:type="string">entity_id</argument>
    <argument name="requestFieldName" xsi:type="string">entity_id</argument>
    <argument name="data" xsi:type="array">
    <item name="config" xsi:type="array">
        <item name="update_url" xsi:type="url" path="mui/index/render"/>
    </item>
    </argument>
    </argument>
    <argument name="data" xsi:type="array">
        <item name="js_config" xsi:type="array">
            <item name="component" xsi:type="string">Magento_Ui/js/grid/provider</item>
        </item>
    </argument>
</dataSource>

Now we need to customize the collection file which we have mentioned in above ui component xml as “Magemeta\Uicomponent\Ui\DataProvider\Product\ProductsDataProvider”.

namespace Magemeta\Uicomponent\Ui\DataProvider\Product;

use Magento\Catalog\Model\ResourceModel\Product\CollectionFactory;

class ProductsDataProvider extends \Magento\Ui\DataProvider\AbstractDataProvider
{

    public function __construct(
        CollectionFactory $collectionFactory,
        $name,
        $primaryFieldName,
        $requestFieldName,
        array $meta = [],
        array $data = []
    ) {
        $collection = $collectionFactory->create();
        parent::__construct(
            $name,
            $primaryFieldName,
            $requestFieldName,
            $meta,
            $data
        );
        $this->collection = $collectionFactory->create()
                          ->addAttributeToSelect('*')
                          ->addAttributeToFilter('price', ['gt' => 200]);
    }
}

Hope this helps you guys!!

Leave a Reply