Magento 2 : Add category filter in producy grid Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern) Announcing the arrival of Valued Associate #679: Cesar Manara Unicorn Meta Zoo #1: Why another podcast?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?

false 'Security alert' from Google - every login generates mails from 'no-reply@accounts.google.com'

My admission is revoked after accepting the admission offer

In search of the origins of term censor, I hit a dead end stuck with the greek term, to censor, λογοκρίνω

What do you call an IPA symbol that lacks a name (e.g. ɲ)?

How to translate "red flag" into Spanish?

How did Elite on the NES work?

Could typically electronic sounds be generated mechanically?

Why is arima in R one time step off?

Could a cockatrice have parasitic embryos?

VBA: Single line if statement with multiple actions

What happened to Viserion in Season 7?

France's Public Holidays' Puzzle

What is the ongoing value of the Kanban board to the developers as opposed to management

Protagonist's race is hidden - should I reveal it?

What to do with someone that cheated their way though university and a PhD program?

Are there existing rules/lore for MTG planeswalkers?

What is the purpose of the side handle on a hand ("eggbeater") drill?

Why isn't everyone flabbergasted about Bran's "gift"?

Does a Draconic Bloodline sorcerer's doubled proficiency bonus for Charisma checks against dragons apply to all dragon types or only the chosen one?

Putting Ant-Man on house arrest

What is the evidence that custom checks in Northern Ireland are going to result in violence?

Is a self contained air-bullet cartridge feasible?

What was Apollo 13's "Little Jolt" after MECO?

Not within Jobscope - Aggravated injury



Magento 2 : Add category filter in producy grid



Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern)
Announcing the arrival of Valued Associate #679: Cesar Manara
Unicorn Meta Zoo #1: Why another podcast?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
    3 hours ago

















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
    3 hours ago













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 3 hours ago









NiketNiket

335




335












  • 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
    3 hours ago

















  • 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
    3 hours ago
















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
3 hours ago





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
3 hours ago










1 Answer
1






active

oldest

votes


















0














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























    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









    0














    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



























      0














      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

























        0












        0








        0







        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 3 hours ago









        Rohan HapaniRohan Hapani

        7,05631865




        7,05631865



























            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

            六本木駅

            Integral that is continuous and looks like it converges to a geometric seriesTesting if a geometric series converges by taking limit to infinitySummation of arithmetic-geometric series of higher orderGeometric series with polynomial exponentHow to Recognize a Geometric SeriesShowing an integral equality with series over the integersDiscontinuity of a series of continuous functionsReasons why a Series ConvergesSum of infinite geometric series with two terms in summationUsing geometric series for computing IntegralsLimit of geometric series sum when $r = 1$

            Joseph Lister