Suppose you need to add filters to your collection in magento 2 and you want to display your grid using ui_component as they allow you to configure the page manipulating the UI components, then follow the steps below.
Now suppose you want to display products whose price is greater than 100.
Add this code in your Webkul/ModuleName/view/adminhtml/ui_component/example.xml
<dataSource name="test_products_data_source"> <argument name="dataProvider" xsi:type="configurableObject"> <argument name="class" xsi:type="string">Webkul\ModuleName\Ui\DataProvider\Product\ProductDataProvider</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>
In the code above,
<argument name=”class” xsi:type=”string”>Webkul\ModuleName\Ui\DataProvider\Product\ProductDataProvider</argument>
this line holds to path to our collection.
Now in file ProductDataProvider.php in path Webkul/ModuleName/Ui/DataProvider/Product
namespace Webkul\ModuleName\Ui\DataProvider\Product; use Magento\Catalog\Model\ResourceModel\Product\CollectionFactory; class ProductDataProvider 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' => 100]); } }
And that’s it. Follow the rest like you normally do to display a grid.
Happy coding 🙂
with your blog , I can modified collection in grid but I want to update the product name in grid with third party api product content , How can I acheive this?