Back to Top

How to add category column with filter to the Admin product grid in Magento 2

Updated 18 July 2023

As per the magento functionality, we can assign multiple categories to products. By default, you can not filter the products on the basis of categories. So today we will learn how to add a category column with a filter to the product grid.

Here we will use the webkul sample module. https://webkul.com/blog/magento-development-01-module-registration/

Step 1 :- Webkul/BlogManager/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="Webkul\BlogManager\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="Webkul\BlogManager\Ui\Component\Listing\Column\Category">
            <argument name="data" xsi:type="array">
                <item name="options" xsi:type="object">Webkul\BlogManager\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 :- Webkul/BlogManager/Ui/Component/Listing/Column/Category.php

<?php
namespace Webkul\BlogManager\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 :- Webkul/BlogManager/Model/Category/Categorylist.php

Start your headless eCommerce
now.
Find out More
<?php
namespace Webkul\BlogManager\Model\Category;

class CategoryList implements \Magento\Framework\Option\ArrayInterface
{
    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 :- Webkul/BlogManager/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="Webkul\BlogManager\Ui\DataProvider\Product\ProductDataProvider" />
</config>

Step 5 :- Webkul/BlogManager/Ui/DataProvider/Product/ProductDataProvider.php

<?php
namespace Webkul\BlogManager\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);
        }
    }
}

Here you can find the similar extension Marketplace vendor categories

Screenshot-from-2023-07-04-20-50-30

Thanks and Happy coding 🙂

. . .

Leave a Comment

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


2 comments

  • Dipu Chandra Dey
    • Kartik Upadhyay (Moderator)
  • Back to Top

    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home