How To

How to Add Category Column with Filter to the Admin Product Grid in Magento 2?

Hello Magento Friends,

Today I will explain How to Add Category Column with Filter to the Admin Product Grid in Magento 2.

One of the key features of Magento 2 is its customizable admin interface, allowing store owners to tailor the system to meet their specific needs. By default, Magento 2’s Admin Product Grid provides essential information about products, such as SKU, name, price, and stock status. However, for store administrators dealing with a wide range of products, it becomes crucial to have additional information readily available, such as the category to which each product belongs. Adding a Category column with a filter can significantly improve the user experience and streamline product management tasks.

In this blog post, we will explore how to enhance the Admin Product Grid in Magento 2 by adding a Category column with a filter, providing administrators with a convenient way to manage products.

Steps to Add Category Column with Filter to the Admin Product Grid in Magento 2:

Step 1: Create a product_listing.xml file inside the view folder.

app\code\Vendor\Module\view\adminhtml\ui_component\

Then add the code as follows

<?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\Module\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\Module\Ui\Component\Listing\Column\Category">
            <argument name="data" xsi:type="array">
                <item name="options" xsi:type="object">Vendor\Module\Model\Category\Categorylist</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: Now, create a Category.php file inside the view folder.

app\code\Vendor\Module\Ui\Component\Listing\Column\

Then include the code as given below

<?php
namespace Vendor\Module\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: Next, create Categorylist.php file inside etc folder.

app\code\Vendor\Module\Model\Category\

And add the below-mentioned code

<?php
namespace Vendor\Module\Model\Category;

class CategoryList implements \Magento\Framework\Option\ArrayInterface
{
    protected  $collectionFactory;
    protected $_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: Then create di.xml file inside etc folder.

app\code\Vendor\Module\etc\

And add the following code snippet

<?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\Module\Ui\DataProvider\Product\ProductDataProvider" />
</config>

Step 5: At last, create ProductDataProvider.php file inside etc folder.

app\code\Vendor\Module\Ui\DataProvider\Product\

Now include the below given piece of code

<?php
namespace Vendor\Module\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);
        }
    }
}

Output: 

You can see that the category has been added to the filter options in your Magento 2 admin.

On selecting it, the category column will be displayed in the Magento 2 product admin grid.

Conclusion:

Enhancing the Admin Product Grid in Magento 2 by adding a Category column with a filter provides a valuable tool for store administrators. This customization allows for more efficient product management, making it easier to organize and categorize a large inventory. By following the steps outlined in this blog post, you can empower your team to navigate the admin interface with greater ease and precision, ultimately improving the overall efficiency of your online store management.

Related Article – How to Filter by Multiple SKU on Admin Product Grid in Magento 2?

If you have any doubts, let me know through the comment section. Share the tutorial with your friends, and stay in touch with us for more.

Happy Coding!

Click to rate this post!
[Total: 1 Average: 5]
Dhiren Vasoya

Dhiren Vasoya is a Director and Co-founder at MageComp, Passionate ?️ Certified Magento Developer?‍?. He has more than 9 years of experience in Magento Development and completed 850+ projects to solve the most important E-commerce challenges. He is fond❤️ of coding and if he is not busy developing then you can find him at the cricket ground, hitting boundaries.?

Recent Posts

How to Add Tooltip in Checkout Shipping Field in Magento 2?

Hello Magento Friends, In today’s blog, I will explain How to Add Tooltip in Checkout…

2 days ago

How to Integrate and Use MongoDB with Laravel?

MongoDB is a popular NoSQL database that offers flexibility and scalability when handling modern web…

3 days ago

NodeJS | Callback Function

In NodeJS, callbacks empower developers to execute asynchronous operations like reading files, handling requests, and…

4 days ago

How to Show SKU in Order Summary in Magento 2?

Hello Magento Friends, In today’s blog, we will learn How to Show SKU in Order…

6 days ago

Best Colors to Use for CTA Buttons

The "Buy Now" and "Add to Cart" buttons serve as the primary call-to-action (CTA) elements…

1 week ago

Magento 2: How to Save Custom Field Value to quote_address for Multi-Shipping Orders

Hello Magento Friends, In Magento 2, the checkout process allows customers to choose multiple shipping…

1 week ago