Magento 2 : Add category filter in producy gridmagento admin product grid add category filter to admin grid without adding columnHow to filter orders grid with order items quantity total weight?Magento Store filter in Order grid?How add admin grid in magento 2.0.6To add category filter in Product grid magento2Magento 2 : Filter Product Grid Using Category In AdminMagento 2 : Add category filter to product gridMagento 2 Admin Grid Filter lost on reloadMagento 2 : Category name filter in product grid in custom moduleCondition on Category Filter in New Product Page?

How to write a column outside the braces in a matrix?

How to have a sharp product image?

As an international instructor, should I openly talk about my accent?

Get consecutive integer number ranges from list of int

How come there are so many candidates for the 2020 Democratic party presidential nomination?

Aliens crash on Earth and go into stasis to wait for technology to fix their ship

Phrase for the opposite of "foolproof"

How to not starve gigantic beasts

Can SQL Server create collisions in system generated constraint names?

Don’t seats that recline flat defeat the purpose of having seatbelts?

I preordered a game on my Xbox while on the home screen of my friend's account. Which of us owns the game?

Mistake in years of experience in resume?

How to limit Drive Letters Windows assigns to new removable USB drives

How to pronounce 'c++' in Spanish

Elements other than carbon that can form many different compounds by bonding to themselves?

On The Origin of Dissonant Chords

What happens to Mjolnir (Thor's hammer) at the end of Endgame?

Apply MapThread to all but one variable

a sore throat vs a strep throat vs strep throat

Classification of surfaces

"The cow" OR "a cow" OR "cows" in this context

How does Captain America channel this power?

How do I check if a string is entirely made of the same substring?

What are the steps to solving this definite integral?



Magento 2 : Add category filter in producy grid


magento admin product grid add category filter to admin grid without adding columnHow to filter orders grid with order items quantity total weight?Magento Store filter in Order grid?How add admin grid in magento 2.0.6To add category filter in Product grid magento2Magento 2 : Filter Product Grid Using Category In AdminMagento 2 : Add category filter to product gridMagento 2 Admin Grid Filter lost on reloadMagento 2 : Category name filter in product grid in custom moduleCondition on Category Filter in New Product Page?






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








0















In admin, I want to add column of category and also add category filter in product grid.



How to do this?



Please help me.



Thanks.










share|improve this question






















  • Can you add a bit more detail? Are you referencing the layered navigation that magento offers? I'm not sure what you mean by 'column of category'. Here are the docs for layered navigation: docs.magento.com/m2/ee/user_guide/catalog/…

    – mlunt
    Apr 23 at 17:48

















0















In admin, I want to add column of category and also add category filter in product grid.



How to do this?



Please help me.



Thanks.










share|improve this question






















  • Can you add a bit more detail? Are you referencing the layered navigation that magento offers? I'm not sure what you mean by 'column of category'. Here are the docs for layered navigation: docs.magento.com/m2/ee/user_guide/catalog/…

    – mlunt
    Apr 23 at 17:48













0












0








0








In admin, I want to add column of category and also add category filter in product grid.



How to do this?



Please help me.



Thanks.










share|improve this question














In admin, I want to add column of category and also add category filter in product grid.



How to do this?



Please help me.



Thanks.







magento2 admin category filter






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Apr 23 at 17:35









NiketNiket

355




355












  • Can you add a bit more detail? Are you referencing the layered navigation that magento offers? I'm not sure what you mean by 'column of category'. Here are the docs for layered navigation: docs.magento.com/m2/ee/user_guide/catalog/…

    – mlunt
    Apr 23 at 17:48

















  • Can you add a bit more detail? Are you referencing the layered navigation that magento offers? I'm not sure what you mean by 'column of category'. Here are the docs for layered navigation: docs.magento.com/m2/ee/user_guide/catalog/…

    – mlunt
    Apr 23 at 17:48
















Can you add a bit more detail? Are you referencing the layered navigation that magento offers? I'm not sure what you mean by 'column of category'. Here are the docs for layered navigation: docs.magento.com/m2/ee/user_guide/catalog/…

– mlunt
Apr 23 at 17:48





Can you add a bit more detail? Are you referencing the layered navigation that magento offers? I'm not sure what you mean by 'column of category'. Here are the docs for layered navigation: docs.magento.com/m2/ee/user_guide/catalog/…

– mlunt
Apr 23 at 17:48










1 Answer
1






active

oldest

votes


















1














To add category column in product grid, add this below code in your product_listing.xml file :



<?xml version="1.0" encoding="UTF-8"?>
<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">
<argument name="data" xsi:type="array">
<item name="config" xsi:type="array">
<item name="filterOptions" xsi:type="boolean">true</item>
<item name="levelsVisibility" xsi:type="number">1</item>
</item>
</argument>
<settings>
<options class="VendorModuleModelCategoryCategoryList"/>
<caption translate="true">– Please Select a Category –</caption>
<label translate="true">Categories</label>
<dataScope>category_id</dataScope>
<imports>
<link name="visible">componentType = column, index = $ $.index :visible</link>
</imports>
</settings>
</filterSelect>
</filters>
</listingToolbar>
<columns name="product_columns" class="MagentoCatalogUiComponentListingColumns">
<column name="category_id" class="VendorModuleUiComponentListingColumnCategory">
<argument name="data" xsi:type="array">
<item name="config" xsi:type="array">
<item name="label" xsi:type="string" translate="true">Categories</item>
<item name="sortOrder" xsi:type="number">35</item>
</item>
</argument>
</column>
</columns>
</listing>


Now, we need to override prepareDataSource() method. To get category values in the prepareDataSource() method like below code :




VendorModuleUiComponentListingColumnCategory.php




<?php

namespace VendorModuleUiComponentListingColumn;

use MagentoFrameworkViewElementUiComponentFactory;
use MagentoFrameworkViewElementUiComponentContextInterface;

class Category extends MagentoUiComponentListingColumnsColumn


/**
* @var MagentoCatalogModelProductFactory
*/
private $productFactory;

/**
* @var MagentoCatalogModelCategoryFactory
*/
private $categoryFactory;

/**
* [__construct description]
* @param ContextInterface $context [description]
* @param UiComponentFactory $uiComponentFactory [description]
* @param array $components [description]
* @param array $data [description]
* @param MagentoCatalogModelProductFactory $productFactory [description]
* @param MagentoCatalogModelCategoryFactory $categoryFactory [description]
*/
public function __construct(
ContextInterface $context,
UiComponentFactory $uiComponentFactory,
array $components = [],
array $data = [],
MagentoCatalogModelProductFactory $productFactory,
MagentoCatalogModelCategoryFactory $categoryFactory
)
parent::__construct($context, $uiComponentFactory, $components, $data);
$this->productFactory = $productFactory;
$this->categoryFactory = $categoryFactory;


/**
* Prepare date for category column
* @param array $dataSource [description]
* @return array
*/
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->productFactory->create()->load($productId);
$categoryIds = $product->getCategoryIds();
$categories = [];
if (count($categoryIds))
foreach ($categoryIds as $categoryId)
$categoryData = $this->categoryFactory->create()->load($categoryId);
$categories[] = $categoryData->getName();


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


return $dataSource;




create di.xml file for override class :



<?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="MagentoCatalogUiDataProviderProductProductDataProvider" type="VendorModuleUiDataProviderProductProductDataProvider" />
</config>


Now, add method addFilter() to VendorModuleUiDataProviderProductProductDataProvider.php



<?php

namespace VendorModuleUiDataProviderProduct;

class ProductDataProvider extends MagentoCatalogUiDataProviderProductProductDataProvider

/**
* For filter grid according to category
* @param MagentoFrameworkApiFilter $filter
*/
public function addFilter(MagentoFrameworkApiFilter $filter)

if ($filter->getField() == 'category_id')
$this->getCollection()->addCategoriesFilter(['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);





And last to add Options to the category filter dropdown :




VendorModuleModelCategoryCategoryList.php




<?php

namespace VendorModuleModelCategory;

use MagentoCatalogModelCategory as CategoryModel;

class CategoryList implements MagentoFrameworkOptionArrayInterface


/**
* @var MagentoCatalogModelResourceModelCategoryCollectionFactory
*/
private $categoryCollectionFactory;
/**
* [__construct description]
* @param MagentoCatalogModelResourceModelCategoryCollectionFactory $collectionFactory [description]
*/
public function __construct(
MagentoCatalogModelResourceModelCategoryCollectionFactory $collectionFactory
)
$this->categoryCollectionFactory = $collectionFactory;


/**
* Get list of categories
* @return array
*/
public function toOptionArray()

$collection = $this->categoryCollectionFactory->create();
$collection->addAttributeToSelect(['name', 'is_active', 'parent_id']);
$categoryById = [
CategoryModel::TREE_ROOT_ID => [
'value' => CategoryModel::TREE_ROOT_ID,
'optgroup' => null,
],
];
foreach ($collection as $category)
foreach ([$category->getId(), $category->getParentId()] as $categoryId)
if (!isset($categoryById[$categoryId]))
$categoryById[$categoryId] = ['value' => $categoryId];



$categoryById[$category->getId()]['is_active'] = $category->getIsActive();
$categoryById[$category->getId()]['label'] = $category->getName();
$categoryById[$category->getParentId()]['optgroup'][] = &$categoryById[$category->getId()];


return $categoryById[CategoryModel::TREE_ROOT_ID]['optgroup'];




Hope, It will helpful for you.






share|improve this answer


















  • 1





    Thanks man ..!!! It's working :)

    – Niket
    Apr 24 at 2:55











Your Answer








StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "479"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: false,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: null,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);













draft saved

draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fmagento.stackexchange.com%2fquestions%2f271134%2fmagento-2-add-category-filter-in-producy-grid%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









1














To add category column in product grid, add this below code in your product_listing.xml file :



<?xml version="1.0" encoding="UTF-8"?>
<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">
<argument name="data" xsi:type="array">
<item name="config" xsi:type="array">
<item name="filterOptions" xsi:type="boolean">true</item>
<item name="levelsVisibility" xsi:type="number">1</item>
</item>
</argument>
<settings>
<options class="VendorModuleModelCategoryCategoryList"/>
<caption translate="true">– Please Select a Category –</caption>
<label translate="true">Categories</label>
<dataScope>category_id</dataScope>
<imports>
<link name="visible">componentType = column, index = $ $.index :visible</link>
</imports>
</settings>
</filterSelect>
</filters>
</listingToolbar>
<columns name="product_columns" class="MagentoCatalogUiComponentListingColumns">
<column name="category_id" class="VendorModuleUiComponentListingColumnCategory">
<argument name="data" xsi:type="array">
<item name="config" xsi:type="array">
<item name="label" xsi:type="string" translate="true">Categories</item>
<item name="sortOrder" xsi:type="number">35</item>
</item>
</argument>
</column>
</columns>
</listing>


Now, we need to override prepareDataSource() method. To get category values in the prepareDataSource() method like below code :




VendorModuleUiComponentListingColumnCategory.php




<?php

namespace VendorModuleUiComponentListingColumn;

use MagentoFrameworkViewElementUiComponentFactory;
use MagentoFrameworkViewElementUiComponentContextInterface;

class Category extends MagentoUiComponentListingColumnsColumn


/**
* @var MagentoCatalogModelProductFactory
*/
private $productFactory;

/**
* @var MagentoCatalogModelCategoryFactory
*/
private $categoryFactory;

/**
* [__construct description]
* @param ContextInterface $context [description]
* @param UiComponentFactory $uiComponentFactory [description]
* @param array $components [description]
* @param array $data [description]
* @param MagentoCatalogModelProductFactory $productFactory [description]
* @param MagentoCatalogModelCategoryFactory $categoryFactory [description]
*/
public function __construct(
ContextInterface $context,
UiComponentFactory $uiComponentFactory,
array $components = [],
array $data = [],
MagentoCatalogModelProductFactory $productFactory,
MagentoCatalogModelCategoryFactory $categoryFactory
)
parent::__construct($context, $uiComponentFactory, $components, $data);
$this->productFactory = $productFactory;
$this->categoryFactory = $categoryFactory;


/**
* Prepare date for category column
* @param array $dataSource [description]
* @return array
*/
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->productFactory->create()->load($productId);
$categoryIds = $product->getCategoryIds();
$categories = [];
if (count($categoryIds))
foreach ($categoryIds as $categoryId)
$categoryData = $this->categoryFactory->create()->load($categoryId);
$categories[] = $categoryData->getName();


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


return $dataSource;




create di.xml file for override class :



<?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="MagentoCatalogUiDataProviderProductProductDataProvider" type="VendorModuleUiDataProviderProductProductDataProvider" />
</config>


Now, add method addFilter() to VendorModuleUiDataProviderProductProductDataProvider.php



<?php

namespace VendorModuleUiDataProviderProduct;

class ProductDataProvider extends MagentoCatalogUiDataProviderProductProductDataProvider

/**
* For filter grid according to category
* @param MagentoFrameworkApiFilter $filter
*/
public function addFilter(MagentoFrameworkApiFilter $filter)

if ($filter->getField() == 'category_id')
$this->getCollection()->addCategoriesFilter(['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);





And last to add Options to the category filter dropdown :




VendorModuleModelCategoryCategoryList.php




<?php

namespace VendorModuleModelCategory;

use MagentoCatalogModelCategory as CategoryModel;

class CategoryList implements MagentoFrameworkOptionArrayInterface


/**
* @var MagentoCatalogModelResourceModelCategoryCollectionFactory
*/
private $categoryCollectionFactory;
/**
* [__construct description]
* @param MagentoCatalogModelResourceModelCategoryCollectionFactory $collectionFactory [description]
*/
public function __construct(
MagentoCatalogModelResourceModelCategoryCollectionFactory $collectionFactory
)
$this->categoryCollectionFactory = $collectionFactory;


/**
* Get list of categories
* @return array
*/
public function toOptionArray()

$collection = $this->categoryCollectionFactory->create();
$collection->addAttributeToSelect(['name', 'is_active', 'parent_id']);
$categoryById = [
CategoryModel::TREE_ROOT_ID => [
'value' => CategoryModel::TREE_ROOT_ID,
'optgroup' => null,
],
];
foreach ($collection as $category)
foreach ([$category->getId(), $category->getParentId()] as $categoryId)
if (!isset($categoryById[$categoryId]))
$categoryById[$categoryId] = ['value' => $categoryId];



$categoryById[$category->getId()]['is_active'] = $category->getIsActive();
$categoryById[$category->getId()]['label'] = $category->getName();
$categoryById[$category->getParentId()]['optgroup'][] = &$categoryById[$category->getId()];


return $categoryById[CategoryModel::TREE_ROOT_ID]['optgroup'];




Hope, It will helpful for you.






share|improve this answer


















  • 1





    Thanks man ..!!! It's working :)

    – Niket
    Apr 24 at 2:55















1














To add category column in product grid, add this below code in your product_listing.xml file :



<?xml version="1.0" encoding="UTF-8"?>
<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">
<argument name="data" xsi:type="array">
<item name="config" xsi:type="array">
<item name="filterOptions" xsi:type="boolean">true</item>
<item name="levelsVisibility" xsi:type="number">1</item>
</item>
</argument>
<settings>
<options class="VendorModuleModelCategoryCategoryList"/>
<caption translate="true">– Please Select a Category –</caption>
<label translate="true">Categories</label>
<dataScope>category_id</dataScope>
<imports>
<link name="visible">componentType = column, index = $ $.index :visible</link>
</imports>
</settings>
</filterSelect>
</filters>
</listingToolbar>
<columns name="product_columns" class="MagentoCatalogUiComponentListingColumns">
<column name="category_id" class="VendorModuleUiComponentListingColumnCategory">
<argument name="data" xsi:type="array">
<item name="config" xsi:type="array">
<item name="label" xsi:type="string" translate="true">Categories</item>
<item name="sortOrder" xsi:type="number">35</item>
</item>
</argument>
</column>
</columns>
</listing>


Now, we need to override prepareDataSource() method. To get category values in the prepareDataSource() method like below code :




VendorModuleUiComponentListingColumnCategory.php




<?php

namespace VendorModuleUiComponentListingColumn;

use MagentoFrameworkViewElementUiComponentFactory;
use MagentoFrameworkViewElementUiComponentContextInterface;

class Category extends MagentoUiComponentListingColumnsColumn


/**
* @var MagentoCatalogModelProductFactory
*/
private $productFactory;

/**
* @var MagentoCatalogModelCategoryFactory
*/
private $categoryFactory;

/**
* [__construct description]
* @param ContextInterface $context [description]
* @param UiComponentFactory $uiComponentFactory [description]
* @param array $components [description]
* @param array $data [description]
* @param MagentoCatalogModelProductFactory $productFactory [description]
* @param MagentoCatalogModelCategoryFactory $categoryFactory [description]
*/
public function __construct(
ContextInterface $context,
UiComponentFactory $uiComponentFactory,
array $components = [],
array $data = [],
MagentoCatalogModelProductFactory $productFactory,
MagentoCatalogModelCategoryFactory $categoryFactory
)
parent::__construct($context, $uiComponentFactory, $components, $data);
$this->productFactory = $productFactory;
$this->categoryFactory = $categoryFactory;


/**
* Prepare date for category column
* @param array $dataSource [description]
* @return array
*/
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->productFactory->create()->load($productId);
$categoryIds = $product->getCategoryIds();
$categories = [];
if (count($categoryIds))
foreach ($categoryIds as $categoryId)
$categoryData = $this->categoryFactory->create()->load($categoryId);
$categories[] = $categoryData->getName();


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


return $dataSource;




create di.xml file for override class :



<?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="MagentoCatalogUiDataProviderProductProductDataProvider" type="VendorModuleUiDataProviderProductProductDataProvider" />
</config>


Now, add method addFilter() to VendorModuleUiDataProviderProductProductDataProvider.php



<?php

namespace VendorModuleUiDataProviderProduct;

class ProductDataProvider extends MagentoCatalogUiDataProviderProductProductDataProvider

/**
* For filter grid according to category
* @param MagentoFrameworkApiFilter $filter
*/
public function addFilter(MagentoFrameworkApiFilter $filter)

if ($filter->getField() == 'category_id')
$this->getCollection()->addCategoriesFilter(['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);





And last to add Options to the category filter dropdown :




VendorModuleModelCategoryCategoryList.php




<?php

namespace VendorModuleModelCategory;

use MagentoCatalogModelCategory as CategoryModel;

class CategoryList implements MagentoFrameworkOptionArrayInterface


/**
* @var MagentoCatalogModelResourceModelCategoryCollectionFactory
*/
private $categoryCollectionFactory;
/**
* [__construct description]
* @param MagentoCatalogModelResourceModelCategoryCollectionFactory $collectionFactory [description]
*/
public function __construct(
MagentoCatalogModelResourceModelCategoryCollectionFactory $collectionFactory
)
$this->categoryCollectionFactory = $collectionFactory;


/**
* Get list of categories
* @return array
*/
public function toOptionArray()

$collection = $this->categoryCollectionFactory->create();
$collection->addAttributeToSelect(['name', 'is_active', 'parent_id']);
$categoryById = [
CategoryModel::TREE_ROOT_ID => [
'value' => CategoryModel::TREE_ROOT_ID,
'optgroup' => null,
],
];
foreach ($collection as $category)
foreach ([$category->getId(), $category->getParentId()] as $categoryId)
if (!isset($categoryById[$categoryId]))
$categoryById[$categoryId] = ['value' => $categoryId];



$categoryById[$category->getId()]['is_active'] = $category->getIsActive();
$categoryById[$category->getId()]['label'] = $category->getName();
$categoryById[$category->getParentId()]['optgroup'][] = &$categoryById[$category->getId()];


return $categoryById[CategoryModel::TREE_ROOT_ID]['optgroup'];




Hope, It will helpful for you.






share|improve this answer


















  • 1





    Thanks man ..!!! It's working :)

    – Niket
    Apr 24 at 2:55













1












1








1







To add category column in product grid, add this below code in your product_listing.xml file :



<?xml version="1.0" encoding="UTF-8"?>
<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">
<argument name="data" xsi:type="array">
<item name="config" xsi:type="array">
<item name="filterOptions" xsi:type="boolean">true</item>
<item name="levelsVisibility" xsi:type="number">1</item>
</item>
</argument>
<settings>
<options class="VendorModuleModelCategoryCategoryList"/>
<caption translate="true">– Please Select a Category –</caption>
<label translate="true">Categories</label>
<dataScope>category_id</dataScope>
<imports>
<link name="visible">componentType = column, index = $ $.index :visible</link>
</imports>
</settings>
</filterSelect>
</filters>
</listingToolbar>
<columns name="product_columns" class="MagentoCatalogUiComponentListingColumns">
<column name="category_id" class="VendorModuleUiComponentListingColumnCategory">
<argument name="data" xsi:type="array">
<item name="config" xsi:type="array">
<item name="label" xsi:type="string" translate="true">Categories</item>
<item name="sortOrder" xsi:type="number">35</item>
</item>
</argument>
</column>
</columns>
</listing>


Now, we need to override prepareDataSource() method. To get category values in the prepareDataSource() method like below code :




VendorModuleUiComponentListingColumnCategory.php




<?php

namespace VendorModuleUiComponentListingColumn;

use MagentoFrameworkViewElementUiComponentFactory;
use MagentoFrameworkViewElementUiComponentContextInterface;

class Category extends MagentoUiComponentListingColumnsColumn


/**
* @var MagentoCatalogModelProductFactory
*/
private $productFactory;

/**
* @var MagentoCatalogModelCategoryFactory
*/
private $categoryFactory;

/**
* [__construct description]
* @param ContextInterface $context [description]
* @param UiComponentFactory $uiComponentFactory [description]
* @param array $components [description]
* @param array $data [description]
* @param MagentoCatalogModelProductFactory $productFactory [description]
* @param MagentoCatalogModelCategoryFactory $categoryFactory [description]
*/
public function __construct(
ContextInterface $context,
UiComponentFactory $uiComponentFactory,
array $components = [],
array $data = [],
MagentoCatalogModelProductFactory $productFactory,
MagentoCatalogModelCategoryFactory $categoryFactory
)
parent::__construct($context, $uiComponentFactory, $components, $data);
$this->productFactory = $productFactory;
$this->categoryFactory = $categoryFactory;


/**
* Prepare date for category column
* @param array $dataSource [description]
* @return array
*/
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->productFactory->create()->load($productId);
$categoryIds = $product->getCategoryIds();
$categories = [];
if (count($categoryIds))
foreach ($categoryIds as $categoryId)
$categoryData = $this->categoryFactory->create()->load($categoryId);
$categories[] = $categoryData->getName();


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


return $dataSource;




create di.xml file for override class :



<?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="MagentoCatalogUiDataProviderProductProductDataProvider" type="VendorModuleUiDataProviderProductProductDataProvider" />
</config>


Now, add method addFilter() to VendorModuleUiDataProviderProductProductDataProvider.php



<?php

namespace VendorModuleUiDataProviderProduct;

class ProductDataProvider extends MagentoCatalogUiDataProviderProductProductDataProvider

/**
* For filter grid according to category
* @param MagentoFrameworkApiFilter $filter
*/
public function addFilter(MagentoFrameworkApiFilter $filter)

if ($filter->getField() == 'category_id')
$this->getCollection()->addCategoriesFilter(['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);





And last to add Options to the category filter dropdown :




VendorModuleModelCategoryCategoryList.php




<?php

namespace VendorModuleModelCategory;

use MagentoCatalogModelCategory as CategoryModel;

class CategoryList implements MagentoFrameworkOptionArrayInterface


/**
* @var MagentoCatalogModelResourceModelCategoryCollectionFactory
*/
private $categoryCollectionFactory;
/**
* [__construct description]
* @param MagentoCatalogModelResourceModelCategoryCollectionFactory $collectionFactory [description]
*/
public function __construct(
MagentoCatalogModelResourceModelCategoryCollectionFactory $collectionFactory
)
$this->categoryCollectionFactory = $collectionFactory;


/**
* Get list of categories
* @return array
*/
public function toOptionArray()

$collection = $this->categoryCollectionFactory->create();
$collection->addAttributeToSelect(['name', 'is_active', 'parent_id']);
$categoryById = [
CategoryModel::TREE_ROOT_ID => [
'value' => CategoryModel::TREE_ROOT_ID,
'optgroup' => null,
],
];
foreach ($collection as $category)
foreach ([$category->getId(), $category->getParentId()] as $categoryId)
if (!isset($categoryById[$categoryId]))
$categoryById[$categoryId] = ['value' => $categoryId];



$categoryById[$category->getId()]['is_active'] = $category->getIsActive();
$categoryById[$category->getId()]['label'] = $category->getName();
$categoryById[$category->getParentId()]['optgroup'][] = &$categoryById[$category->getId()];


return $categoryById[CategoryModel::TREE_ROOT_ID]['optgroup'];




Hope, It will helpful for you.






share|improve this answer













To add category column in product grid, add this below code in your product_listing.xml file :



<?xml version="1.0" encoding="UTF-8"?>
<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">
<argument name="data" xsi:type="array">
<item name="config" xsi:type="array">
<item name="filterOptions" xsi:type="boolean">true</item>
<item name="levelsVisibility" xsi:type="number">1</item>
</item>
</argument>
<settings>
<options class="VendorModuleModelCategoryCategoryList"/>
<caption translate="true">– Please Select a Category –</caption>
<label translate="true">Categories</label>
<dataScope>category_id</dataScope>
<imports>
<link name="visible">componentType = column, index = $ $.index :visible</link>
</imports>
</settings>
</filterSelect>
</filters>
</listingToolbar>
<columns name="product_columns" class="MagentoCatalogUiComponentListingColumns">
<column name="category_id" class="VendorModuleUiComponentListingColumnCategory">
<argument name="data" xsi:type="array">
<item name="config" xsi:type="array">
<item name="label" xsi:type="string" translate="true">Categories</item>
<item name="sortOrder" xsi:type="number">35</item>
</item>
</argument>
</column>
</columns>
</listing>


Now, we need to override prepareDataSource() method. To get category values in the prepareDataSource() method like below code :




VendorModuleUiComponentListingColumnCategory.php




<?php

namespace VendorModuleUiComponentListingColumn;

use MagentoFrameworkViewElementUiComponentFactory;
use MagentoFrameworkViewElementUiComponentContextInterface;

class Category extends MagentoUiComponentListingColumnsColumn


/**
* @var MagentoCatalogModelProductFactory
*/
private $productFactory;

/**
* @var MagentoCatalogModelCategoryFactory
*/
private $categoryFactory;

/**
* [__construct description]
* @param ContextInterface $context [description]
* @param UiComponentFactory $uiComponentFactory [description]
* @param array $components [description]
* @param array $data [description]
* @param MagentoCatalogModelProductFactory $productFactory [description]
* @param MagentoCatalogModelCategoryFactory $categoryFactory [description]
*/
public function __construct(
ContextInterface $context,
UiComponentFactory $uiComponentFactory,
array $components = [],
array $data = [],
MagentoCatalogModelProductFactory $productFactory,
MagentoCatalogModelCategoryFactory $categoryFactory
)
parent::__construct($context, $uiComponentFactory, $components, $data);
$this->productFactory = $productFactory;
$this->categoryFactory = $categoryFactory;


/**
* Prepare date for category column
* @param array $dataSource [description]
* @return array
*/
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->productFactory->create()->load($productId);
$categoryIds = $product->getCategoryIds();
$categories = [];
if (count($categoryIds))
foreach ($categoryIds as $categoryId)
$categoryData = $this->categoryFactory->create()->load($categoryId);
$categories[] = $categoryData->getName();


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


return $dataSource;




create di.xml file for override class :



<?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="MagentoCatalogUiDataProviderProductProductDataProvider" type="VendorModuleUiDataProviderProductProductDataProvider" />
</config>


Now, add method addFilter() to VendorModuleUiDataProviderProductProductDataProvider.php



<?php

namespace VendorModuleUiDataProviderProduct;

class ProductDataProvider extends MagentoCatalogUiDataProviderProductProductDataProvider

/**
* For filter grid according to category
* @param MagentoFrameworkApiFilter $filter
*/
public function addFilter(MagentoFrameworkApiFilter $filter)

if ($filter->getField() == 'category_id')
$this->getCollection()->addCategoriesFilter(['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);





And last to add Options to the category filter dropdown :




VendorModuleModelCategoryCategoryList.php




<?php

namespace VendorModuleModelCategory;

use MagentoCatalogModelCategory as CategoryModel;

class CategoryList implements MagentoFrameworkOptionArrayInterface


/**
* @var MagentoCatalogModelResourceModelCategoryCollectionFactory
*/
private $categoryCollectionFactory;
/**
* [__construct description]
* @param MagentoCatalogModelResourceModelCategoryCollectionFactory $collectionFactory [description]
*/
public function __construct(
MagentoCatalogModelResourceModelCategoryCollectionFactory $collectionFactory
)
$this->categoryCollectionFactory = $collectionFactory;


/**
* Get list of categories
* @return array
*/
public function toOptionArray()

$collection = $this->categoryCollectionFactory->create();
$collection->addAttributeToSelect(['name', 'is_active', 'parent_id']);
$categoryById = [
CategoryModel::TREE_ROOT_ID => [
'value' => CategoryModel::TREE_ROOT_ID,
'optgroup' => null,
],
];
foreach ($collection as $category)
foreach ([$category->getId(), $category->getParentId()] as $categoryId)
if (!isset($categoryById[$categoryId]))
$categoryById[$categoryId] = ['value' => $categoryId];



$categoryById[$category->getId()]['is_active'] = $category->getIsActive();
$categoryById[$category->getId()]['label'] = $category->getName();
$categoryById[$category->getParentId()]['optgroup'][] = &$categoryById[$category->getId()];


return $categoryById[CategoryModel::TREE_ROOT_ID]['optgroup'];




Hope, It will helpful for you.







share|improve this answer












share|improve this answer



share|improve this answer










answered Apr 23 at 18:01









Rohan HapaniRohan Hapani

7,16931865




7,16931865







  • 1





    Thanks man ..!!! It's working :)

    – Niket
    Apr 24 at 2:55












  • 1





    Thanks man ..!!! It's working :)

    – Niket
    Apr 24 at 2:55







1




1





Thanks man ..!!! It's working :)

– Niket
Apr 24 at 2:55





Thanks man ..!!! It's working :)

– Niket
Apr 24 at 2:55

















draft saved

draft discarded
















































Thanks for contributing an answer to Magento Stack Exchange!


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fmagento.stackexchange.com%2fquestions%2f271134%2fmagento-2-add-category-filter-in-producy-grid%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Get product attribute by attribute group code in magento 2get product attribute by product attribute group in magento 2Magento 2 Log Bundle Product Data in List Page?How to get all product attribute of a attribute group of Default attribute set?Magento 2.1 Create a filter in the product grid by new attributeMagento 2 : Get Product Attribute values By GroupMagento 2 How to get all existing values for one attributeMagento 2 get custom attribute of a single product inside a pluginMagento 2.3 How to get all the Multi Source Inventory (MSI) locations collection in custom module?Magento2: how to develop rest API to get new productsGet product attribute by attribute group code ( [attribute_group_code] ) in magento 2

Category:9 (number) SubcategoriesMedia in category "9 (number)"Navigation menuUpload mediaGND ID: 4485639-8Library of Congress authority ID: sh85091979ReasonatorScholiaStatistics

Magento 2.3: How do i solve this, Not registered handle, on custom form?How can i rewrite TierPrice Block in Magento2magento 2 captcha not rendering if I override layout xmlmain.CRITICAL: Plugin class doesn't existMagento 2 : Problem while adding custom button order view page?Magento 2.2.5: Overriding Admin Controller sales/orderMagento 2.2.5: Add, Update and Delete existing products Custom OptionsMagento 2.3 : File Upload issue in UI Component FormMagento2 Not registered handleHow to configured Form Builder Js in my custom magento 2.3.0 module?Magento 2.3. How to create image upload field in an admin form