How To Add Category Column With Filter To The Admin Product Grid In Magento 2

Hello Everyone,

In this blog, we will learn about how to Add Category Columns with filters to the Admin Product Grid in Magento 2.

By default Magento 2 Admin Product grid provides information about products such as name, price, SKU etc.

Adding a category column with a filter improves the user experience.

Without wasting your time, let us guide you straight away. Follow the easy step given below to Add Category Column with filter to the Admin Product Grid in Magento 2.

STEPS FOR ADD CATEGORY COLUMN WITH FILTER TO THE ADMIN PRODUCT GRID IN MAGENTO 2

Step 1: Create file product_listing.xml

app/code/Vendor/Extension/view/adminhtml/ui_component/product_listing.xml

<?xml version="1.0" ?>

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

     <listingToolbar name="listing_top">

         <filters name="listing_filters">

            <filterSelect name="category_id" provider="${ $.parentName }" component="Magento_Ui/js/form/element/ui-select" template="ui/grid/filters/elements/ui-select">

                <settings>

                    <options class="Vendor\Extension\Model\Category\Categorylist"/>

                    <caption translate="true">Select...</caption>

                    <label translate="true">Category</label>

                    <dataScope>category_id</dataScope>

                </settings>

            </filterSelect>

        </filters>

    </listingToolbar>

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

        <column name="category_id" class="Vendor\Extension\Ui\Component\Listing\Column\Category">

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

                <item name="options" xsi:type="object">Vendor\Extension\Model\Category\Category List</item>

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

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

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

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

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

                </item>

            </argument>

        </column>

    </columns>

</listing>

Step 2: Create file Category.php

app/code/Vendor/Extension/Ui/Component/Listing/Column/Category.php

<?php

namespace Vendor\Extension\Ui\Component\Listing\Column;

use Magento\Framework\View\Element\UiComponentFactory;

use Magento\Framework\View\Element\UiComponent\ContextInterface;

use Magento\Framework\Api\SearchCriteriaBuilder;

use Magento\Framework\UrlInterface;

class Category extends \Magento\Ui\Component\Listing\Columns\Column

{

    /**

     * Constructor.

     *

     * @param ContextInterface   $context

     * @param UiComponentFactory $uiComponentFactory

     * @param SearchCriteriaBuilder $criteria

     * @param \Magento\Catalog\Model\ProductFactory $product

     * @param \Magento\Catalog\Model\CategoryFactory $category

     * @param  UrlInterface $urlBuilder

     * @param array $data

     */

    public function __construct(

        ContextInterface $context,

        UiComponentFactory $uiComponentFactory,

        SearchCriteriaBuilder $criteria,

        \Magento\Catalog\Model\ProductFactory $product,

        \Magento\Catalog\Model\CategoryFactory $category,

        UrlInterface $urlBuilder,

        array $components = [],

        array $data = [])

    {

        $this->_urlBuilder = $urlBuilder;

        $this->_searchCriteria = $criteria;

        $this->product = $product;

        $this->category = $category;

        parent::__construct($context, $uiComponentFactory, $components, $data);

    }

    public function prepareDataSource(array $dataSource)

    {

        $fieldName = $this->getData('name');

        if (isset($dataSource['data']['items'])) {

            foreach ($dataSource['data']['items'] as & $item) {

                $productId = $item['entity_id'];

                $product = $this->product->create()->load($productId);

                $cats = $product->getCategoryIds();

                $categories = [];

                if (count($cats)) {

                    foreach ($cats as $cat) {

                        $category = $this->category->create()->load($cat);

                        $categories[] = $category->getName();

                    }

                }

                $item[$fieldName] = implode(',', $categories);

            }

        }

        return $dataSource;

    }

}

Step 3: Create file Categorylist.php

app/code/Vendor/Extension/Model/Category/Categorylist.php

<?php

namespace Vendor\Extension\Model\Category;

class CategoryList implements \Magento\Framework\Option\ArrayInterface

{

    private $categoryCollectionFactory;

    public function __construct(

        \Magento\Catalog\Model\ResourceModel\Category\CollectionFactory $collectionFactory

    ) {

        $this->categoryCollectionFactory = $collectionFactory;

    }

    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;

    }

}

Step 4: Create file di.xml

app/code/Vendor/Extension/etc/di.xml

<?xml version="1.0"?>

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">

    <preference for="Magento\Catalog\Ui\DataProvider\Product\ProductDataProvider" type="Vendor\Extension\Ui\DataProvider\Product\ProductDataProvider" />

</config>

Step 5: Create file ProductDataProvider.php

app/code/Vendor/Extension/Ui/DataProvider/Product/ProductDataProvider.php

<?php

namespace Vendor\Extension\Ui\DataProvider\Product;

class ProductDataProvider extends \Magento\Catalog\Ui\DataProvider\Product\ProductDataProvider

{

    public function addFilter(\Magento\Framework\Api\Filter $filter)

    {

        if ($filter->getField() == 'category_id') {

            $this->getCollection()->addCategoriesFilter(['in' => $filter->getValue()]);

        } else {

            parent::addFilter($filter);

        }

    }

}

Step 6: Finally run the below commands

$ php bin/magento setup:upgrade

$ php bin/magento cache:clean

$ php bin/magento cache:flush


Step 7: Output:

Final Thoughts:

So this was the easiest way which we have told you in this blog. This is how you can Add Category Column with filter to the Admin Product Grid in Magento 2. Hope you liked the blog.

So quickly go to the comment box and tell me how you like this blog?

Stay tuned with us on our site to get new updates of Magento.

Thanks for reading and visiting our site.

How useful was this post?

Click on a star to rate it!

Average rating 5 / 5. Vote count: 1

No votes so far! Be the first to rate this post.

Leave a Reply

Your email address will not be published. Required fields are marked *