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?
What language was spoken in East Asia before Proto-Turkic?
How to reduce LED flash rate (frequency)
How to have a sharp product image?
How do I deal with a coworker that keeps asking to make small superficial changes to a report, and it is seriously triggering my anxiety?
Binary Numbers Magic Trick
how to find the equation of a circle given points of the circle
Does holding a wand and speaking its command word count as V/S/M spell components?
Is there really no use for MD5 anymore?
What is the difference between `command a[bc]d` and `command `ab,cd`
What is the most expensive material in the world that could be used to create Pun-Pun's lute?
Realistic Necromancy?
How do I reattach a shelf to the wall when it ripped out of the wall?
Is there a way to get a compiler for the original B programming language?
Apply MapThread to all but one variable
Do I have to worry about players making “bad” choices on level up?
How come there are so many candidates for the 2020 Democratic party presidential nomination?
What do the phrase "Reeyan's seacrest" and the word "fraggle" mean in a sketch?
How did Captain America manage to do this?
French for 'It must be my imagination'?
What is the strongest case that can be made in favour of the UK regaining some control over fishing policy after Brexit?
How to make a pipeline wait for end-of-file or stop after an error?
Was there a Viking Exchange as well as a Columbian one?
How much cash can I safely carry into the USA and avoid civil forfeiture?
With a Canadian student visa, can I spend a night at Vancouver before continuing to Toronto?
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;
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
add a comment |
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
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
add a comment |
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
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
magento2 admin category filter
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
add a comment |
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
add a comment |
1 Answer
1
active
oldest
votes
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.
1
Thanks man ..!!! It's working :)
– Niket
Apr 24 at 2:55
add a comment |
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
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
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.
1
Thanks man ..!!! It's working :)
– Niket
Apr 24 at 2:55
add a comment |
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.
1
Thanks man ..!!! It's working :)
– Niket
Apr 24 at 2:55
add a comment |
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.
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.
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
add a comment |
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
add a comment |
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.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
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
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