6

I used Magento 2.1 and want to add new filter in the product grid. But when I added my module the website loading forever. Please help me to solve the problem. I have searched on the internet, but I didn't see any similar problem.
Bellow my code:

etc/adminhtml/di.xml

<type name="Magento\Catalog\Ui\DataProvider\Product\ProductDataProvider">
    <arguments>
        <argument name="addFieldStrategies" xsi:type="array">
            <item name="configurable_options" xsi:type="object">Training\Unit6\Ui\DataProvider\Product\AddConfigurableOptionsToCollection</item>
        </argument>
    </arguments>
</type>

Ui/Component/Listing/Column/Options.php

namespace Training\Unit6\Ui\Component\Listing\Column;

class Options implements \Magento\Framework\Data\OptionSourceInterface
{
    protected $options;
    public function toOptionArray()
    {
        $this->options = [
            [
                'label' => ' ',
                'value' => 0
            ],
            [
                'label' => 'One',
                'value' => 1
            ],
            [
                'label' => 'Two',
                'value' => 2
            ],
            [
                'label' => 'Three',
                'value' => 3
            ],
        ];
        return $this->options;
    }
}

Ui/DataProvider/Product/AddConfigurableOptionsToCollection.php

namespace Training\Unit6\Ui\DataProvider\Product;

use Magento\Ui\DataProvider\AddFilterToCollectionInterface;
use Magento\ConfigurableProduct\Model\ResourceModel\Product\Type\Configurable\Attribute\Collection as ConfigurableCollection;
use Magento\Framework\Data\Collection;

class AddConfigurableOptionsToCollection implements AddFilterToCollectionInterface {

    protected $configurableOptions = null;

    public function __construct(ConfigurableCollection $collection) {
        $this->configurableOptions = $collection;
    }

    public function addFilter(Collection $collection, $field, $condition = null) {
        if (isset($condition['eq']) && ($numberOfOptions = $condition['eq'])) {

            $select = $this->configurableOptions->getSelect()
                ->reset(\Zend_Db_Select::COLUMNS)
                ->columns(array('product_id', 'COUNT(*) as cnt'))
                ->group('product_id');

            $res = $this->configurableOptions->getConnection()->fetchAll($select);

            $ids = array();
            foreach ($res as $opt) {
                if ($opt['cnt'] == $numberOfOptions) {
                    $ids[] = $opt['product_id'];
                }
            }
            $collection->addFieldToFilter('entity_id', array('in' => $ids));
        }
    }

}

view/adminhtml/ui_component/product_listing.xml

<container name="listing_top">
    <filters name="listing_filters">
        <filterSelect name="configurable_options">
            <argument name="optionsProvider" xsi:type="configurableObject">
                <argument name="class" xsi:type="string">Training\Unit6\Ui\Component\Listing\Column\Options</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">configurable_options</item>
                    <item name="caption" xsi:type="string" translate="true">Select...</item>
                    <item name="label" xsi:type="string" translate="true">Configurable options</item>
                </item>
            </argument>
        </filterSelect>
    </filters>
</container>

Here is my module https://www.dropbox.com/s/lt6riovjaju4se9/unit6.zip?dl=0

1
  • 1
    No need to add any custom code. Only setting admin side in attribute Add to Column Options : Yes & Use in Filter Options : Yes under Advanced Attribute Properties
    – Abdul
    Commented May 8, 2017 at 4:50

4 Answers 4

5

No need to add any custom code. In magento2.x available default setting under the attribute

Go admin side Stores -> Attributes -> Product and open your created attribute

After click Advanced Attribute Properties tab under the Properties tab and set Yes below two fields

  1. Use in Filter Options: Yes (Select "Yes" to add this attribute to the list of filter options in the product grid.)
  2. Add to Column Options: Yes (Select "Yes" to add this attribute to the list of column options in the product grid. )

After saving attribute and check product grid.

Please see the attached screenshot.

enter image description here

2
  • 3
    Thanks @Abdul. I know I can show that on the config product attribute. But I have many environments (dev, staging, live). I can't remember all changes when I deploy, I need change by code, but your comment is great.
    – Trang Lee
    Commented May 8, 2017 at 7:50
  • 1
    Sorry I can't vote your comment because my account don't enough reputation.
    – Trang Lee
    Commented May 8, 2017 at 8:00
4

In the view/adminhtml/ui_component/product_listing.xml

Change <container name="listing_top"> to <listingToolbar name="listing_top"> it's worked.

1

I have found the solution. I follow by https://github.com/DRAJI/Categoryfilter. It's worked. But I don't know how to keep the filter field and remove that field in product grid? enter image description here

Here is my code:

etc/di.xml

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<preference for="Magento\Catalog\Ui\DataProvider\Product\ProductDataProvider" type="Training\Unit6\Ui\DataProvider\Product\AddProductSeriesOptionsToCollection"/>
</config>

view/adminhtml/ui_component/product_listing.xml

<?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">
    </listingToolbar>
        <column name="product_series" class="Training\Unit6\Ui\Component\Listing\Column\ProductSeries">
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="filter" xsi:type="string">text</item>
                    <item name="add_field" xsi:type="boolean">false</item>
                    <item name="dataType" xsi:type="string">text</item>
                    <item name="label" xsi:type="string" translate="true">Product series</item>
                    <item name="sortOrder" xsi:type="number">100</item>
                </item>
            </argument>
        </column>
    </columns>
</listing>

Ui/Component/Listing/Column/ProductSeries.php

namespace Training\Unit6\Ui\Component\Listing\Column;
use Magento\Framework\View\Element\UiComponentFactory;
use Magento\Framework\View\Element\UiComponent\ContextInterface;
/**
 * Class Price
 */
class ProductSeries extends \Magento\Ui\Component\Listing\Columns\Column
{
    protected $_productloader;
    public function __construct(
        ContextInterface $context,
        UiComponentFactory $uiComponentFactory,
        \Magento\Catalog\Model\ProductFactory $_productloader,
        array $components = [],
        array $data = []
    ) {
        parent::__construct($context,$uiComponentFactory, $components, $data);
        $this->_productloader = $_productloader;
    }
    /**
     * Prepare Data Source
     *
     * @param array $dataSource
     * @return array
     */
    public function prepareDataSource(array $dataSource)
    {
        //$fieldName = $this->getData('name');
        return $dataSource;
    }
}

Ui/DataProvider/Product/AddProductSeriesOptionsToCollection.php

namespace Training\Unit6\Ui\DataProvider\Product;
class AddProductSeriesOptionsToCollection extends \Magento\Catalog\Ui\DataProvider\Product\ProductDataProvider
{
    public function addFilter(\Magento\Framework\Api\Filter $filter)
    {
        if($filter->getField()=='unit6'){
            $this->getCollection()->addCategoriesFilter(array('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);
        }
    }
}
0

namespace Training\Unit6\Ui\Component\Listing\Column; use Magento\Framework\View\Element\UiComponentFactory; use Magento\Framework\View\Element\UiComponent\ContextInterface; /**

  • Class Price / class ProductSeries extends \Magento\Ui\Component\Listing\Columns\Column { protected $_productloader; public function __construct( ContextInterface $context, UiComponentFactory $uiComponentFactory, \Magento\Catalog\Model\ProductFactory $_productloader, array $components = [], array $data = [] ) { parent::__construct($context,$uiComponentFactory, $components, $data); $this->_productloader = $_productloader; } /*
    • Prepare Data Source
    • @param array $dataSource
    • @return array */ public function prepareDataSource(array $dataSource) { //$fieldName = $this->getData('name'); return $dataSource; } } Ui/DataProvider/Product/AddProductSeriesOptionsToCollection.php

namespace Training\Unit6\Ui\DataProvider\Product; class AddProductSeriesOptionsToCollection extends \Magento\Catalog\Ui\DataProvider\Product\ProductDataProvider { public function addFilter(\Magento\Framework\Api\Filter $filter) { if($filter->getField()=='unit6'){ $this->getCollection()->addCategoriesFilter(array('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); } } } Share Improve this answer Follow edited May 8, 2017 at 8:25 answered May 8, 2017 at 8:14 Trang Lee's user avatar Trang Lee 13411 gold badge11 silver badge1010 bronze badges Add a comment Your Answer

Your Answer

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

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