Magento 2, PHP

Magento2 : Add Category filter to Product Grid in

Magento 2 UI components allow to generate and display several list and grid types. As well you can create your own component based on the already existing code.

Adding a new column to a grid is not so complex task as distinct from creation a column with filtering. We can add a category filter in product grid by the following way

First, to add Category column to Product grid

app/code/Done/Productsgrid/view/adminhtml/ui_component/product_listing.xml

<?xml version="1.0" encoding="UTF-8"?>

<listing xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance&#8221; xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Ui:etc / ui_configuration.xsd ">

 <listingToolbar name="listing_top">

</listingToolbar>

<columns name="product_columns" class="Magento\Catalog\Ui\Component\Listing\Columns">

<column name="category_ids" class="Done\Productsgrid\Ui\Component\Listing\Column\Category">

<argument name="data" xsi:type="array">

<item name="options" xsi:type="object">Done\Productsgrid\Model\Category\Categorylist</item>

<item name="config" xsi:type="array">

<item name="filter" xsi:type="string">select</item>

<item name="add_field" xsi:type="boolean">true</item>

<item name="dataType" xsi:type="string">select</item>

<item name="label" xsi:type="string" translate="true">Categories</item>

<item name="sortOrder" xsi:type="number">100</item>

</item>

</argument>

</column>

</columns>

</listing>

We add the column into Product grid.

We should override the prepareDataSource() method: Get category values to the in prepareDataSource method like below in app/code/Done/Productsgrid/Ui/Component/Listing/Column/Category.php

public function prepareDataSource(array $dataSource)
{
    $fieldName = $this->getData(‘name’);
    if (isset($dataSource[‘data’][‘items’])) {
        foreach ($dataSource[‘data’][‘items’] as & $item) {
            //print_r($item);die;
            $p_id=$item[‘entity_id’];
            $product=$this->_productloader->create()->load($p_id);
            $cats = $product->getCategoryIds();
            $objectManager   = \Magento\Framework\App\ObjectManager::getInstance();
            $categories=array();
            if(count($cats) ){
                foreach($cats as $cat){
                    $category = $objectManager->create(‘Magento\Catalog\Model\Category’)->load($cat);
                    $categories[]=$category->getName();
                }
            }
            $item[$fieldName]=implode(‘,’,$categories);
        }
    }
    return $dataSource;
}

After doing it, Clear the cache. Thus we can fill the row the data.

To add category filter by in line

<item name=”filter” xsi:type=”string”>select</item>

To add Options to the category filter dropdown

<item name=”options” xsi:type=”object”>Done\Productsgrid\Model\Category\Categorylist</item>

app/code/Done/Productsgrid/Model/Category/Categorylist.php

 public function toOptionArray($addEmpty = true)
    {
        $collection = $this->_categoryCollectionFactory->create();
        $collection->addAttributeToSelect(‘name’);
        $options = [];
        if ($addEmpty) {
            $options[] = [‘label’ => __(‘– Please Select a Category –‘), ‘value’ => ”];
        }
        foreach ($collection as $category) {
            $options[] = [‘label’ => $category->getName(), ‘value’ => $category->getId()];
        }
    
        return $options;
    }

we use the collection as a source for filtering. And now, all that we have to do is to override a Ui Dataprovider, which could add our data into filtering results.

app/code/Done/Productsgrid/etc/di.xml

<preference for=”Magento\Catalog\Ui\DataProvider\Product\ProductDataProvider” type=”Done\Productsgrid\Ui\DataProvider\Product\ProductDataProvider” />

And add method addFilter to app/code/Done/Productsgrid/Ui/DataProvider/Product/ProductDataProvider.php

 public function addFilter(\Magento\Framework\Api\Filter $filter)
    {
        if($filter->getField()==’category_ids’){
            $this->getCollection()->addCategoriesFilter(array(‘in’ => $filter->getValue()));
        }
        elseif (isset($this->addFilterStrategies[$filter->getField()])) {
            $this->addFilterStrategies[$filter->getField()]
            ->addFilter(
                $this->getCollection(),
                $filter->getField(),
                [$filter->getConditionType() => $filter->getValue()]
                );
        } else {
            parent::addFilter($filter);
        }
    }

Filtering by the current field should be available after override Ui Dataprovider. That’s it!

Github: https://github.com/durgagupta/product-grid.git

Tags :