Magento – How to get Product Collection For Custom Grid Module

gridmagento-2.1productsuicomponent

I have created a custom module and want to display products with my custom filters.

I am confused if I need to create models and extend it with product models ? so I can add them in di.xml to show products in my custom module grid.

Or is there any other way around.

Edit

Ok I tried this looking at magento-catalog I prodivded a data provider as magento does. Now I am getting the grid , but now when I try to multiselect the products I dont get the selected ids in Param

This are the params I get when I multiselect from grid.

Array
(
    [key] => 3a7750c8654fbe63017744ebcbc877e39923539800d9d22c6529d8a2bee4891c
    [excluded] => false
    [filters] => Array
        (
            [placeholder] => true
        )

    [namespace] => vendor_module_productlisting
    [form_key] => vkXFki8YOWNHkcrm
)

Ui Grid vendor_module_productlisting.xml

<dataSource name="vendor_module_productlisting_data_source">
    <argument name="dataProvider" xsi:type="configurableObject">
        <argument name="class" xsi:type="string">Vendor\Module\Ui\DataProvider\Product\ProductDataProvider</argument>
        <argument name="name" xsi:type="string">vendor_module_productlisting_data_source</argument>
        <argument name="primaryFieldName" xsi:type="string">entity_id</argument>
        <argument name="requestFieldName" xsi:type="string">id</argument>
        <argument name="data" xsi:type="array">
            <item name="config" xsi:type="array">
                <item name="component" xsi:type="string">Magento_Ui/js/grid/provider</item>
                <item name="update_url" path="mui/index/render" xsi:type="url"/>
                <item name="storageConfig" xsi:type="array">
                    <item name="indexField" xsi:type="string">entity_id</item>
                </item>
            </item>
        </argument>
    </argument>
</dataSource>

My Data Prodvider

<?php
/**
 * Copyright © 2016 Magento. All rights reserved.
 * See COPYING.txt for license details.
 */
namespace Vendor\Module\Ui\DataProvider\Product;

use Magento\Catalog\Model\ResourceModel\Product\CollectionFactory;

/**
 * Class ProductDataProvider
 */
class ProductDataProvider extends \Magento\Ui\DataProvider\AbstractDataProvider
{
    /**
     * Product collection
     *
     * @var \Magento\Catalog\Model\ResourceModel\Product\Collection
     */
    protected $collection;

    /**
     * @var \Magento\Ui\DataProvider\AddFieldToCollectionInterface[]
     */
    protected $addFieldStrategies;

    /**
     * @var \Magento\Ui\DataProvider\AddFilterToCollectionInterface[]
     */
    protected $addFilterStrategies;

    protected $categoryCollection;

    public function __construct(
        $name,
        $primaryFieldName,
        $requestFieldName,
        CollectionFactory $collectionFactory,
        \Vendor\Module\Model\ResourceModel\Categories\CollectionFactory $vendorCatCollectionFactory,
        array $addFieldStrategies = [],
        array $addFilterStrategies = [],
        array $meta = [],
        array $data = []
    ) {
        parent::__construct($name, $primaryFieldName, $requestFieldName, $meta, $data);
        $this->collection = $collectionFactory->create();
        $this->categoryCollection = $vendorCatCollectionFactory->create();
        $this->addFieldStrategies = $addFieldStrategies;
        $this->addFilterStrategies = $addFilterStrategies;
    }


    protected function _getCategoriesIds(){
       return [1,2,3];
    }

    public function getData()
    {

        $categories = $this->_getCategoriesIds();

        $this->collection->addAttributeToSelect(['name', 'image'], 'inner')->addCategoriesFilter(['in' => $categories]);
        $items = $this->collection->toArray();

        return [
            'totalRecords' => $this->collection->getSize(),
            'items' => array_values($items),
        ];
    }

    /**
     * Add field to select
     *
     * @param string|array $field
     * @param string|null $alias
     * @return void
     */
    public function addField($field, $alias = null)
    {
        if (isset($this->addFieldStrategies[$field])) {
            $this->addFieldStrategies[$field]->addField($this->getCollection(), $field, $alias);
        } else {
            parent::addField($field, $alias);
        }
    }

    /**
     * {@inheritdoc}
     */
    public function addFilter(\Magento\Framework\Api\Filter $filter)
    {
        if (isset($this->addFilterStrategies[$filter->getField()])) {
            $this->addFilterStrategies[$filter->getField()]
                ->addFilter(
                    $this->getCollection(),
                    $filter->getField(),
                    [$filter->getConditionType() => $filter->getValue()]
                );
        } else {
            parent::addFilter($filter);
        }
    }
}

Has to be a better way ? 🙁

Best Answer

No need of extend with product mode. simple inject in __construct method and use it.

protected $productCollectionFactory;

public function __construct(
        .....
        \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollectionFactory,
        .....
    ) {
       ......
        $this->productCollectionFactory = $productCollectionFactory;
       ....
    }

you can get the collection

$collection = $this->productCollectionFactory->create();
Related Topic