2

I have the following in my custom module helper:

public function __construct(
  \Magento\Framework\App\Helper\Context $context,
  \Magento\Catalog\Model\ResourceModel\Product\Collection $productCollection,
  array $data = []
) {
  $this->_productCollection = $productCollection;
  parent::__construct($context);
}

and use the following method:

/**
 * Get the product collection filtered by field
 *
 * @param $field
 * @param $value
 * @return $this
 */
public function getProductCollection($field, $value)
{
    $collection = $this->_productCollection->load();
    $collection->addFilter($field, $value);
    return $collection;
}

In my controller I call the method as such to get all products of type 'simple':

$products = $this->dataHelper->getProductCollection('type_id', 'simple');

However, this doesn't work as it gives me all products, no matter what type.

I can get the type when I use:

$products->getTypeId();

How do I correctly filter my collection my type_id?

6

Please, remove load() from the line $this->_productCollection->load();, because you can not filter the collections that has already been loaded.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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