3

I am implementing Grid for categories collection using UI component.

I have used the following code

Vendor/Module/view/adminhtml/layout/vendor_index_index.xml

 <body>
     <referenceContainer name="content">
        <uiComponent name="vendor_manage_listing"/>
     </referenceContainer>
 </body>

Vendor/Module/view/adminhtml/ui_component/vendor_manage_listing.xml

<columns name="seoreport_category_columns">
        <selectionsColumn name="ids">
            <settings>
                <indexField>entity_id</indexField>
            </settings>
        </selectionsColumn>

        <column name="entity_id">
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="filter" xsi:type="string">text</item>
                    <item name="editor" xsi:type="array">
                        <item name="editorType" xsi:type="string">text</item>
                        <item name="validation" xsi:type="array">
                            <item name="required-entry" xsi:type="boolean">true</item>
                        </item>
                    </item>
                    <item name="label" xsi:type="string" translate="true">Category Id</item>
                </item>
            </argument>
        </column>
        <column name="value">
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="filter" xsi:type="string">false</item>
                    <item name="label" xsi:type="string" translate="true">Category Name</item>
                </item>
            </argument>
        </column>
        <column name="is_active">
        <argument name="data" xsi:type="array">
            <item name="options" xsi:type="object">Vendor\Module\Model\Config\Source\Status</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="dataType" xsi:type="string">select</item>
                <item name="label" translate="true" xsi:type="string">Category Status</item>
            </item>
        </argument>
    </column>
   </columns>

Vendor/Module/Model/ResourceModel/Category.php

<?php
use Magento\Framework\Model\ResourceModel\Db\AbstractDb;
class Category extends  AbstractDb
{

  protected function _construct()
   {
      /* Main Table Name */
     $this->_init('catalog_category_entity','entity_id');
   }
}

Vendor/Module/Model/ResourceModel/Category/Collection.php

<?php

class Collection extends AbstractCollection
{
  protected function _construct()
  {
    $this->_init('Vendor\Module\Model\Category', 
    'Vendor\Module\Model\ResourceModel\Category');
   }
protected function _initSelect()
{
    parent::_initSelect();
     return $this;
   }
}

Vendor/Module/Model/ResourceModel/Category/Grid/Collection.php

<?php 
use Magento\Framework\Api\Search\SearchResultInterface;
use Magento\Framework\Api\Search\AggregationInterface;
use Vendor\Module\Model\ResourceModel\Category\Collection as EntityCollection;

class Collection extends EntityCollection implements SearchResultInterface
{

   protected $aggregations;
   protected $request; 
    public function __construct(
    \Magento\Framework\Data\Collection\EntityFactoryInterface $entityFactory,
    \Psr\Log\LoggerInterface $logger,
    \Magento\Framework\Data\Collection\Db\FetchStrategyInterface $fetchStrategy,
    \Magento\Framework\Event\ManagerInterface $eventManager,
    \Magento\Store\Model\StoreManagerInterface $storeManager,
    $mainTable,
    $eventPrefix,
    $eventObject,
    $resourceModel,
    $model = 'Magento\Framework\View\Element\UiComponent\DataProvider\Document',
    \Magento\Framework\DB\Adapter\AdapterInterface $connection = null,
    \Magento\Framework\Model\ResourceModel\Db\AbstractDb $resource = null,
    \Magento\Framework\App\Request\Http $request
) {
    parent::__construct(
        $entityFactory,
        $logger,
        $fetchStrategy,
        $eventManager,
        $connection,
        $resource
        $this->request = $request;
    );
    $this->_eventPrefix = $eventPrefix;
    $this->_eventObject = $eventObject;
    $this->_init($model, $resourceModel);
    $this->setMainTable($mainTable);
   }

/**
 * @return AggregationInterface
 */
 public function getAggregations()
  {
    return $this->aggregations;
  }
  public function setItems(array $items = null)
  {
    return $this;
  }
 protected function _renderFiltersBefore()
 {
    $filters = $this->request->getParam('filters');
    if (isset($filters['is_active'])) {
        $is_active = $filters['is_active'];
        if ($is_active == 0) {
            $this->getSelect()->orWhere("main_table.is_active = 1");
        }
    }

    parent::_renderFiltersBefore();
  }
}

Vendor\Module\Model\Config\Source\Status.php

use Magento\Framework\Option\ArrayInterface;

class Status implements ArrayInterface
{
   public function toOptionArray()
   {
      $result = [];
        foreach ($this->getOptions() as $value => $label) {
           $result[] = [
             'value' => $value,
             'label' => $label,
           ];
      }

       return $result;
   }

   public function getOptions()
   {
       return [
          '1' => __('All Categories'),
          '0' => __('Visible Categories')
       ];
   }
}

If the first option selected I need to load all categories if the second option is selected I need to show only categories which are enabled.

I am looking for below 2 solutions.

1.Filter should work once applied

2.I have to show Category Status only in Filter not in Column.

How can we implement above functionality. Someone please help me on this. Thanks in Advance!!

5
  • For ui grid filter? Feb 24, 2020 at 8:32
  • Have you Vendor\Module\Model\ResourceModel\Category\Grid\Collection file? Feb 24, 2020 at 8:37
  • @DhadukMitesh, Yes I have that file, updated in my question Feb 24, 2020 at 8:46
  • I am getting is_active unknown column error @DhadukMitesh Feb 25, 2020 at 3:03
  • Error happens when running php bin/magento s:d:c [24-Oct-2020 22:31:14 UTC] PHP Fatal error: Uncaught Error: Class 'AbstractCollection' not found in Vendor/Module/Model/ResourceModel/Category/Collection.php:3. To fix this error add use Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection; TO Vendor/Module/Model/ResourceModel/Category/Collection.php
    – DarthRez
    Oct 24, 2020 at 23:04

2 Answers 2

8
+100

Add this into your listing xml file

Vendor/Module/view/adminhtml/ui_component

vendor_manage_listing.xml

<container name="listing_top">
.........................................................................
.........................................................................
.........................................................................
        <filters name="listing_filters">
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="columnsProvider" xsi:type="string">vendor_manage_listing.vendor_manage_listing.seoreport_category_columns</item>
                    <item name="storageConfig" xsi:type="array">
                        <item name="provider" xsi:type="string">vendor_manage_listing.vendor_manage_listing.listing_top.bookmarks</item>
                        <item name="namespace" xsi:type="string">current.filters</item>
                    </item>
                    <item name="templates" xsi:type="array">
                        <item name="filters" xsi:type="array">
                            <item name="select" xsi:type="array">
                                <item name="component" xsi:type="string">Magento_Ui/js/form/element/ui-select</item>
                                <item name="template" xsi:type="string">ui/grid/filters/elements/ui-select</item>
                            </item>
                        </item>
                    </item>
                    <item name="childDefaults" xsi:type="array">
                        <item name="provider" xsi:type="string">vendor_manage_listing.vendor_manage_listing.listing_top.listing_filters</item>
                        <item name="imports" xsi:type="array">
                            <item name="visible" xsi:type="string">vendor_manage_listing.vendor_manage_listing.seoreport_category_columns.${ $.index }:visible</item>
                        </item>
                    </item>
                </item>
                <item name="observers" xsi:type="array">
                    <item name="column" xsi:type="string">column</item>
                </item>
            </argument>
            <filterSelect name="is_active">
                <argument name="optionsProvider" xsi:type="configurableObject">
                    <argument name="class" xsi:type="string">Vendor\Module\Model\Config\Source\Status</argument>
                </argument>
                <argument name="data" xsi:type="array">
                    <item name="config" xsi:type="array">
                        <item name="provider" xsi:type="string">${ $.parentName }</item>
                        <item name="imports" xsi:type="array">
                            <item name="visible" xsi:type="string">componentType = column, index = ${ $.index }:visible</item>
                        </item>
                        <item name="dataScope" xsi:type="string">is_active</item>
                        <item name="label" xsi:type="string" translate="true">Category Status</item>
                        <item name="captionValue" xsi:type="string">0</item>
                    </item>
                </argument>
            </filterSelect>
        </filters>
.........................................................................
.........................................................................
.........................................................................
</container>

Vendor\Module\Model\Config\Source

Status.php

<?php

namespace Vendor\Module\Model\Config\Source;

use Magento\Framework\Data\OptionSourceInterface;

class Status implements OptionSourceInterface
{
    public function getOptionArray()
    {
        $options = [];
        $options['0'] = __('Visible Categories');
        $options['1'] = __('All Categories');
        return $options;
    }
    public function getAllOptions()
    {
        $res = $this->getOptions();
        array_unshift($res, ['value' => '', 'label' => '']);
        return $res;
    }
    public function getOptions()
    {
        $res = [];
        foreach ($this->getOptionArray() as $index => $value) {
            $res[] = ['value' => $index, 'label' => $value];
        }
        return $res;
    }
    public function toOptionArray()
    {
        return $this->getOptions();
    }
}

run magento command

php bin/magento s:up
php bin/magento s:s:d -f
php bin/magento c:c
php bin/magento c:f

before filter

enter image description here

after filter enter image description here

I Hope This Helps You

15
  • hi @Msquare, can i remove the column is_active code from the listing file? Feb 24, 2020 at 11:08
  • I tried this but filter not working after Apply filter. Feb 24, 2020 at 11:15
  • above code is ruuning , and you can remove is_active column
    – Msquare
    Feb 24, 2020 at 11:22
  • yes I removed is_active column from listing file, now the filter showing with 3 options, once select any option and apply filter, its not working, getting unknown column is_active error Feb 24, 2020 at 11:23
  • you doing something wrong it's works see my screen shot
    – Msquare
    Feb 24, 2020 at 12:09
3

Add the below code in Vendor/Module/view/adminhtml/ui_component/seoreport_category_listing.xml file in the filters tab.

<filterSelect name="value">
    <argument name="optionsProvider" xsi:type="configurableObject">
        <argument name="class" xsi:type="string">X247commerce\Seoreports\Model\Config\Source\Status</argument>
    </argument>
    <argument name="data" xsi:type="array">
        <item name="config" xsi:type="array">
            <item name="provider" xsi:type="string">${ $.parentName }</item>
            <item name="imports" xsi:type="array">
                <item name="visible" xsi:type="string">componentType = column, index = ${ $.index }:visible</item>
            </item>
            <item name="dataScope" xsi:type="string">value</item>
            <item name="label" xsi:type="string" translate="true">Category Status</item>
            <item name="captionValue" xsi:type="string"></item>
        </item>
    </argument>
</filterSelect>

And remove the is_active column.

Add below function in Vendor\Module\Model\ResourceModel\Category\Collection.php file.

protected function _initSelect()
{
    parent::_initSelect();
    $catalog_category_entity_int = $this->getTable('catalog_category_entity_int');
    $this->getSelect()->joinLeft(
        ['category_entity_int' => $catalog_category_entity_int],
        'main_table.entity_id = category_entity_int.entity_id',
        [
            'main_table.entity_id',
            'category_entity_int.value',
        ]
    );
}

Add below function in Vendor\Module\Model\ResourceModel\Category\Grid\Collection.php file.

protected function _renderFiltersBefore()
{
    $filters = $this->request->getParam('filters');
    if (isset($filters['value'])) {
        $is_active = $filters['value'];
        if ($is_active == 0) {
            $this->getSelect()->orWhere("category_entity_int.value is not null");
        }
        if ($is_active == 1) {
            $this->getSelect()->orWhere("category_entity_int.value = 1");
        }
    }

    parent::_renderFiltersBefore();
}

And then clear cache and check it.

8
  • hi @Dhaduk, I do not have any collection file inside Grid directory, can you please update me full code of that file Feb 24, 2020 at 9:50
  • I did research and updated that file, but still filter is not working, pls check once Feb 24, 2020 at 10:21
  • Check my updated answer. Feb 24, 2020 at 11:37
  • hi @Dhaduk, getting this error in log, Column not found: 1054 Unknown column 'is_active' in 'where clause' Feb 24, 2020 at 11:59
  • Check my updated answer. Feb 24, 2020 at 12:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.