Magento 2: Filter Categories in UI Component












0














I'm using Ui Components to list my object and I have a column categories, where I receive one array with the categories names, Now I want to custom the filter so I had changed the listing.xml and I looks like that:



I was expecting to show in the column the names withe the class,
and the filters with the other.



<column name="category_id" class="BlueInfinityLoyaltyProgramUiComponentListingColumnRegardCategory">
<argument name="data" xsi:type="array">
<item name="options" xsi:type="object">BlueInfinityLoyaltyProgramUiComponentListingColumnRegardFilterCategory</item>
<item name="config" xsi:type="array">
<item name="filter" xsi:type="string">select</item>
<item name="component" xsi:type="string">Magento_Ui/js/grid/columns/select</item>
<item name="editor" xsi:type="string">select</item>
<item name="dataType" xsi:type="string">select</item>
<item name="label" xsi:type="string" translate="true">Regard Categories</item>
<item name="visible" xsi:type="boolean">true</item>
</item>
</argument>
</column>


My BlueInfinityLoyaltyProgramUiComponentListingColumnRegardCategory






/**
* @var string
*/
protected $categoryKey;
/**
* @var CategoryRepositoryInterface
*/
private $categoryCollectionFactory;

/**
* @param ContextInterface $context
* @param UiComponentFactory $uiComponentFactory
* @param CategoryCollectionFactory $categoryCollectionFactory
* @param Escaper $escaper
* @param array $components
* @param array $data
* @param string $categoryKey
*/
public function __construct(
ContextInterface $context,
UiComponentFactory $uiComponentFactory,
CategoryCollectionFactory $categoryCollectionFactory,
Escaper $escaper,
array $components = ,
array $data = ,
$categoryKey = 'category_id'
) {
$this->escaper = $escaper;
$this->categoryKey = $categoryKey;
parent::__construct($context, $uiComponentFactory, $components, $data);
$this->categoryCollectionFactory = $categoryCollectionFactory;
}

/**
* Prepare Data Source
*
* @param array $dataSource
* @return array
* @throws MagentoFrameworkExceptionLocalizedException
*/
public function prepareDataSource(array $dataSource)
{
if (isset($dataSource['data']['items'])) {
foreach ($dataSource['data']['items'] as & $item) {
$item[$this->getData('name')] = $this->prepareItem($item);
}
}

return $dataSource;
}

/**
* Get data
*
* @param array $item
* @return string
* @throws MagentoFrameworkExceptionLocalizedException
*/
protected function prepareItem(array $item)
{
$content = ;
if (!empty($item['category_id'])) {
$origCategories = $item['category_id'];
}

if (empty($origCategories)) {
return '';
}
if (!is_array($origCategories)) {
$origCategories = [$origCategories];
}

$matchingNamesCollection = $this->categoryCollectionFactory->create();

$matchingNamesCollection->addAttributeToSelect('path')
->addAttributeToFilter('entity_id', ['neq' => CategoryModel::TREE_ROOT_ID]);

$shownCategoriesIds = ;

/** @var MagentoCatalogModelCategory $category */
foreach ($matchingNamesCollection as $category) {
foreach (explode('/', $category->getPath()) as $parentId) {
$shownCategoriesIds[$parentId] = 1;
}
}

/* @var $collection MagentoCatalogModelResourceModelCategoryCollection */
$collection = $this->categoryCollectionFactory->create();

$collection->addAttributeToFilter('entity_id', ['in' => array_keys($shownCategoriesIds)])
->addAttributeToSelect(['name', 'is_active', 'parent_id']);

$categoryById = [
CategoryModel::TREE_ROOT_ID => [
'value' => CategoryModel::TREE_ROOT_ID
],
];

foreach ($collection as $category) {
if (in_array($category->getId(),$origCategories))
{
$content = $category['name'];
}
}


return $content;
}


}



and the Filter Category






public function __construct(MagentoCatalogHelperCategory $catalogCategory)
{
$this->_categoryHelper = $catalogCategory;
}

/*
* Return categories helper
*/

public function getStoreCategories($sorted = false, $asCollection = false, $toLoad = true)
{
return $this->_categoryHelper->getStoreCategories($sorted, $asCollection, $toLoad);
}

/*
* Option getter
* @return array
*/
public function toOptionArray()
{


$arr = $this->toArray();
$ret = ;

foreach ($arr as $key => $value) {

$ret = [
'value' => $key,
'label' => $value
];
}

return $ret;
}

/*
* Get options in "key-value" format
* @return array
*/
public function toArray()
{

$categories = $this->getStoreCategories(true, false, true);

$catagoryList = array();
foreach ($categories as $category) {

$catagoryList[$category->getEntityId()] = __($category->getName());
}

return $catagoryList;
}


}



Is there any best practice to achieve this? In this moment I just have one or the other.
Thank you










share|improve this question





























    0














    I'm using Ui Components to list my object and I have a column categories, where I receive one array with the categories names, Now I want to custom the filter so I had changed the listing.xml and I looks like that:



    I was expecting to show in the column the names withe the class,
    and the filters with the other.



    <column name="category_id" class="BlueInfinityLoyaltyProgramUiComponentListingColumnRegardCategory">
    <argument name="data" xsi:type="array">
    <item name="options" xsi:type="object">BlueInfinityLoyaltyProgramUiComponentListingColumnRegardFilterCategory</item>
    <item name="config" xsi:type="array">
    <item name="filter" xsi:type="string">select</item>
    <item name="component" xsi:type="string">Magento_Ui/js/grid/columns/select</item>
    <item name="editor" xsi:type="string">select</item>
    <item name="dataType" xsi:type="string">select</item>
    <item name="label" xsi:type="string" translate="true">Regard Categories</item>
    <item name="visible" xsi:type="boolean">true</item>
    </item>
    </argument>
    </column>


    My BlueInfinityLoyaltyProgramUiComponentListingColumnRegardCategory






    /**
    * @var string
    */
    protected $categoryKey;
    /**
    * @var CategoryRepositoryInterface
    */
    private $categoryCollectionFactory;

    /**
    * @param ContextInterface $context
    * @param UiComponentFactory $uiComponentFactory
    * @param CategoryCollectionFactory $categoryCollectionFactory
    * @param Escaper $escaper
    * @param array $components
    * @param array $data
    * @param string $categoryKey
    */
    public function __construct(
    ContextInterface $context,
    UiComponentFactory $uiComponentFactory,
    CategoryCollectionFactory $categoryCollectionFactory,
    Escaper $escaper,
    array $components = ,
    array $data = ,
    $categoryKey = 'category_id'
    ) {
    $this->escaper = $escaper;
    $this->categoryKey = $categoryKey;
    parent::__construct($context, $uiComponentFactory, $components, $data);
    $this->categoryCollectionFactory = $categoryCollectionFactory;
    }

    /**
    * Prepare Data Source
    *
    * @param array $dataSource
    * @return array
    * @throws MagentoFrameworkExceptionLocalizedException
    */
    public function prepareDataSource(array $dataSource)
    {
    if (isset($dataSource['data']['items'])) {
    foreach ($dataSource['data']['items'] as & $item) {
    $item[$this->getData('name')] = $this->prepareItem($item);
    }
    }

    return $dataSource;
    }

    /**
    * Get data
    *
    * @param array $item
    * @return string
    * @throws MagentoFrameworkExceptionLocalizedException
    */
    protected function prepareItem(array $item)
    {
    $content = ;
    if (!empty($item['category_id'])) {
    $origCategories = $item['category_id'];
    }

    if (empty($origCategories)) {
    return '';
    }
    if (!is_array($origCategories)) {
    $origCategories = [$origCategories];
    }

    $matchingNamesCollection = $this->categoryCollectionFactory->create();

    $matchingNamesCollection->addAttributeToSelect('path')
    ->addAttributeToFilter('entity_id', ['neq' => CategoryModel::TREE_ROOT_ID]);

    $shownCategoriesIds = ;

    /** @var MagentoCatalogModelCategory $category */
    foreach ($matchingNamesCollection as $category) {
    foreach (explode('/', $category->getPath()) as $parentId) {
    $shownCategoriesIds[$parentId] = 1;
    }
    }

    /* @var $collection MagentoCatalogModelResourceModelCategoryCollection */
    $collection = $this->categoryCollectionFactory->create();

    $collection->addAttributeToFilter('entity_id', ['in' => array_keys($shownCategoriesIds)])
    ->addAttributeToSelect(['name', 'is_active', 'parent_id']);

    $categoryById = [
    CategoryModel::TREE_ROOT_ID => [
    'value' => CategoryModel::TREE_ROOT_ID
    ],
    ];

    foreach ($collection as $category) {
    if (in_array($category->getId(),$origCategories))
    {
    $content = $category['name'];
    }
    }


    return $content;
    }


    }



    and the Filter Category






    public function __construct(MagentoCatalogHelperCategory $catalogCategory)
    {
    $this->_categoryHelper = $catalogCategory;
    }

    /*
    * Return categories helper
    */

    public function getStoreCategories($sorted = false, $asCollection = false, $toLoad = true)
    {
    return $this->_categoryHelper->getStoreCategories($sorted, $asCollection, $toLoad);
    }

    /*
    * Option getter
    * @return array
    */
    public function toOptionArray()
    {


    $arr = $this->toArray();
    $ret = ;

    foreach ($arr as $key => $value) {

    $ret = [
    'value' => $key,
    'label' => $value
    ];
    }

    return $ret;
    }

    /*
    * Get options in "key-value" format
    * @return array
    */
    public function toArray()
    {

    $categories = $this->getStoreCategories(true, false, true);

    $catagoryList = array();
    foreach ($categories as $category) {

    $catagoryList[$category->getEntityId()] = __($category->getName());
    }

    return $catagoryList;
    }


    }



    Is there any best practice to achieve this? In this moment I just have one or the other.
    Thank you










    share|improve this question



























      0












      0








      0







      I'm using Ui Components to list my object and I have a column categories, where I receive one array with the categories names, Now I want to custom the filter so I had changed the listing.xml and I looks like that:



      I was expecting to show in the column the names withe the class,
      and the filters with the other.



      <column name="category_id" class="BlueInfinityLoyaltyProgramUiComponentListingColumnRegardCategory">
      <argument name="data" xsi:type="array">
      <item name="options" xsi:type="object">BlueInfinityLoyaltyProgramUiComponentListingColumnRegardFilterCategory</item>
      <item name="config" xsi:type="array">
      <item name="filter" xsi:type="string">select</item>
      <item name="component" xsi:type="string">Magento_Ui/js/grid/columns/select</item>
      <item name="editor" xsi:type="string">select</item>
      <item name="dataType" xsi:type="string">select</item>
      <item name="label" xsi:type="string" translate="true">Regard Categories</item>
      <item name="visible" xsi:type="boolean">true</item>
      </item>
      </argument>
      </column>


      My BlueInfinityLoyaltyProgramUiComponentListingColumnRegardCategory






      /**
      * @var string
      */
      protected $categoryKey;
      /**
      * @var CategoryRepositoryInterface
      */
      private $categoryCollectionFactory;

      /**
      * @param ContextInterface $context
      * @param UiComponentFactory $uiComponentFactory
      * @param CategoryCollectionFactory $categoryCollectionFactory
      * @param Escaper $escaper
      * @param array $components
      * @param array $data
      * @param string $categoryKey
      */
      public function __construct(
      ContextInterface $context,
      UiComponentFactory $uiComponentFactory,
      CategoryCollectionFactory $categoryCollectionFactory,
      Escaper $escaper,
      array $components = ,
      array $data = ,
      $categoryKey = 'category_id'
      ) {
      $this->escaper = $escaper;
      $this->categoryKey = $categoryKey;
      parent::__construct($context, $uiComponentFactory, $components, $data);
      $this->categoryCollectionFactory = $categoryCollectionFactory;
      }

      /**
      * Prepare Data Source
      *
      * @param array $dataSource
      * @return array
      * @throws MagentoFrameworkExceptionLocalizedException
      */
      public function prepareDataSource(array $dataSource)
      {
      if (isset($dataSource['data']['items'])) {
      foreach ($dataSource['data']['items'] as & $item) {
      $item[$this->getData('name')] = $this->prepareItem($item);
      }
      }

      return $dataSource;
      }

      /**
      * Get data
      *
      * @param array $item
      * @return string
      * @throws MagentoFrameworkExceptionLocalizedException
      */
      protected function prepareItem(array $item)
      {
      $content = ;
      if (!empty($item['category_id'])) {
      $origCategories = $item['category_id'];
      }

      if (empty($origCategories)) {
      return '';
      }
      if (!is_array($origCategories)) {
      $origCategories = [$origCategories];
      }

      $matchingNamesCollection = $this->categoryCollectionFactory->create();

      $matchingNamesCollection->addAttributeToSelect('path')
      ->addAttributeToFilter('entity_id', ['neq' => CategoryModel::TREE_ROOT_ID]);

      $shownCategoriesIds = ;

      /** @var MagentoCatalogModelCategory $category */
      foreach ($matchingNamesCollection as $category) {
      foreach (explode('/', $category->getPath()) as $parentId) {
      $shownCategoriesIds[$parentId] = 1;
      }
      }

      /* @var $collection MagentoCatalogModelResourceModelCategoryCollection */
      $collection = $this->categoryCollectionFactory->create();

      $collection->addAttributeToFilter('entity_id', ['in' => array_keys($shownCategoriesIds)])
      ->addAttributeToSelect(['name', 'is_active', 'parent_id']);

      $categoryById = [
      CategoryModel::TREE_ROOT_ID => [
      'value' => CategoryModel::TREE_ROOT_ID
      ],
      ];

      foreach ($collection as $category) {
      if (in_array($category->getId(),$origCategories))
      {
      $content = $category['name'];
      }
      }


      return $content;
      }


      }



      and the Filter Category






      public function __construct(MagentoCatalogHelperCategory $catalogCategory)
      {
      $this->_categoryHelper = $catalogCategory;
      }

      /*
      * Return categories helper
      */

      public function getStoreCategories($sorted = false, $asCollection = false, $toLoad = true)
      {
      return $this->_categoryHelper->getStoreCategories($sorted, $asCollection, $toLoad);
      }

      /*
      * Option getter
      * @return array
      */
      public function toOptionArray()
      {


      $arr = $this->toArray();
      $ret = ;

      foreach ($arr as $key => $value) {

      $ret = [
      'value' => $key,
      'label' => $value
      ];
      }

      return $ret;
      }

      /*
      * Get options in "key-value" format
      * @return array
      */
      public function toArray()
      {

      $categories = $this->getStoreCategories(true, false, true);

      $catagoryList = array();
      foreach ($categories as $category) {

      $catagoryList[$category->getEntityId()] = __($category->getName());
      }

      return $catagoryList;
      }


      }



      Is there any best practice to achieve this? In this moment I just have one or the other.
      Thank you










      share|improve this question















      I'm using Ui Components to list my object and I have a column categories, where I receive one array with the categories names, Now I want to custom the filter so I had changed the listing.xml and I looks like that:



      I was expecting to show in the column the names withe the class,
      and the filters with the other.



      <column name="category_id" class="BlueInfinityLoyaltyProgramUiComponentListingColumnRegardCategory">
      <argument name="data" xsi:type="array">
      <item name="options" xsi:type="object">BlueInfinityLoyaltyProgramUiComponentListingColumnRegardFilterCategory</item>
      <item name="config" xsi:type="array">
      <item name="filter" xsi:type="string">select</item>
      <item name="component" xsi:type="string">Magento_Ui/js/grid/columns/select</item>
      <item name="editor" xsi:type="string">select</item>
      <item name="dataType" xsi:type="string">select</item>
      <item name="label" xsi:type="string" translate="true">Regard Categories</item>
      <item name="visible" xsi:type="boolean">true</item>
      </item>
      </argument>
      </column>


      My BlueInfinityLoyaltyProgramUiComponentListingColumnRegardCategory






      /**
      * @var string
      */
      protected $categoryKey;
      /**
      * @var CategoryRepositoryInterface
      */
      private $categoryCollectionFactory;

      /**
      * @param ContextInterface $context
      * @param UiComponentFactory $uiComponentFactory
      * @param CategoryCollectionFactory $categoryCollectionFactory
      * @param Escaper $escaper
      * @param array $components
      * @param array $data
      * @param string $categoryKey
      */
      public function __construct(
      ContextInterface $context,
      UiComponentFactory $uiComponentFactory,
      CategoryCollectionFactory $categoryCollectionFactory,
      Escaper $escaper,
      array $components = ,
      array $data = ,
      $categoryKey = 'category_id'
      ) {
      $this->escaper = $escaper;
      $this->categoryKey = $categoryKey;
      parent::__construct($context, $uiComponentFactory, $components, $data);
      $this->categoryCollectionFactory = $categoryCollectionFactory;
      }

      /**
      * Prepare Data Source
      *
      * @param array $dataSource
      * @return array
      * @throws MagentoFrameworkExceptionLocalizedException
      */
      public function prepareDataSource(array $dataSource)
      {
      if (isset($dataSource['data']['items'])) {
      foreach ($dataSource['data']['items'] as & $item) {
      $item[$this->getData('name')] = $this->prepareItem($item);
      }
      }

      return $dataSource;
      }

      /**
      * Get data
      *
      * @param array $item
      * @return string
      * @throws MagentoFrameworkExceptionLocalizedException
      */
      protected function prepareItem(array $item)
      {
      $content = ;
      if (!empty($item['category_id'])) {
      $origCategories = $item['category_id'];
      }

      if (empty($origCategories)) {
      return '';
      }
      if (!is_array($origCategories)) {
      $origCategories = [$origCategories];
      }

      $matchingNamesCollection = $this->categoryCollectionFactory->create();

      $matchingNamesCollection->addAttributeToSelect('path')
      ->addAttributeToFilter('entity_id', ['neq' => CategoryModel::TREE_ROOT_ID]);

      $shownCategoriesIds = ;

      /** @var MagentoCatalogModelCategory $category */
      foreach ($matchingNamesCollection as $category) {
      foreach (explode('/', $category->getPath()) as $parentId) {
      $shownCategoriesIds[$parentId] = 1;
      }
      }

      /* @var $collection MagentoCatalogModelResourceModelCategoryCollection */
      $collection = $this->categoryCollectionFactory->create();

      $collection->addAttributeToFilter('entity_id', ['in' => array_keys($shownCategoriesIds)])
      ->addAttributeToSelect(['name', 'is_active', 'parent_id']);

      $categoryById = [
      CategoryModel::TREE_ROOT_ID => [
      'value' => CategoryModel::TREE_ROOT_ID
      ],
      ];

      foreach ($collection as $category) {
      if (in_array($category->getId(),$origCategories))
      {
      $content = $category['name'];
      }
      }


      return $content;
      }


      }



      and the Filter Category






      public function __construct(MagentoCatalogHelperCategory $catalogCategory)
      {
      $this->_categoryHelper = $catalogCategory;
      }

      /*
      * Return categories helper
      */

      public function getStoreCategories($sorted = false, $asCollection = false, $toLoad = true)
      {
      return $this->_categoryHelper->getStoreCategories($sorted, $asCollection, $toLoad);
      }

      /*
      * Option getter
      * @return array
      */
      public function toOptionArray()
      {


      $arr = $this->toArray();
      $ret = ;

      foreach ($arr as $key => $value) {

      $ret = [
      'value' => $key,
      'label' => $value
      ];
      }

      return $ret;
      }

      /*
      * Get options in "key-value" format
      * @return array
      */
      public function toArray()
      {

      $categories = $this->getStoreCategories(true, false, true);

      $catagoryList = array();
      foreach ($categories as $category) {

      $catagoryList[$category->getEntityId()] = __($category->getName());
      }

      return $catagoryList;
      }


      }



      Is there any best practice to achieve this? In this moment I just have one or the other.
      Thank you







      magento2 uicomponent






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited yesterday









      Kirti Nariya

      1,016314




      1,016314










      asked Jun 17 '18 at 19:09









      Miguel BarreiroMiguel Barreiro

      12




      12






















          0






          active

          oldest

          votes











          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%2f230241%2fmagento-2-filter-categories-in-ui-component%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          0






          active

          oldest

          votes








          0






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes
















          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.





          Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


          Please pay close attention to the following guidance:


          • 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%2f230241%2fmagento-2-filter-categories-in-ui-component%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

          An IMO inspired problem

          Management

          Investment