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 Create a Shopify Draft Order in Shopify Remix Using GraphQL?

Shopify's Draft Orders feature is an essential tool for merchants, allowing them to create orders…

10 hours ago

How to Use CSS with Shopify Remix Vite?

CSS (Cascading Style Sheets) is essential in web development to create visually appealing and responsive…

1 day ago

Latest Hyvä Theme Trends to Elevate your Magento UI/UX

Your eCommerce website theme is highly important for your business's online success as it reflects…

2 days ago

Use Hyvä Products at their Full Potential

Hyvä represents more than just a theme; it is a comprehensive suite of extensions and…

2 days ago

Magento 2: Add Number of Products Displayed Per Page in Invoice PDF

Hello Magento mates, Invoices are critical documents in every eCommerce business, providing details of product…

4 days ago

Magento 2: How to Call phtml Based on Selection of Payment Method at Multishipping Payment

Hello Magento Friends, Multishipping in Magento 2 allows customers to split their orders into multiple…

7 days ago