3

I'm working on a custom module to fetch the latest 10 simple products but it doesn't work. Could anyone have a look and see what i'm missing? Thanks

public function getProducts()
{
    /** @var $collection \Magento\Catalog\Model\ResourceModel\Product\Collection */
    $collection = $this->_productCollectionFactory->create();
    $collection->addAttributeToSelect('*')
        ->addAttributeToFilter('type_id', array('eq' => 'simple'))
        ->setOrder('created_at')
        ->setPageSize(10);
    return $collection;
}

2 Answers 2

6

This should do the trick

public function getProducts()
{
    /** @var $collection \Magento\Catalog\Model\ResourceModel\Product\Collection */
    $collection = $this->_productCollectionFactory->create();
    $collection->addAttributeToSelect('*');
    $collection->addAttributeToFilter('type_id', \Magento\Catalog\Model\Product\Type::TYPE_SIMPLE);
    $collection->getSelect()->order('created_at', \Magento\Framework\DB\Select::SQL_DESC);
    $collection->getSelect()->limit(10);
    return $collection;
}

In reference to our discussion from below, copy and paste this exactly as you see. The strange thing is that when I pasted your code into my IDE, it was going nuts with errors saying that it didn't recognize certain characters in your type hint for the product collection factory. It's strange but when I typed it out by hand, all errors went away. Copy and paste exactly as you see:

<?php

namespace Packt\HelloWorld\Block;
use Magento\Framework\View\Element\Template;

class Newproducts extends Template
{
    protected $_productCollectionFactory;

    public function __construct(
        \Magento\Framework\View\Element\Template\Context $context,
        \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollectionFactory,
        array $data = []
    )
    {
        $this->_productCollectionFactory = $productCollectionFactory;
        parent::__construct($context, $data);
    }

    public function getProducts()
    {
        /** @var $collection \Magento\Catalog\Model\ResourceModel\Product\Collection */
        $collection = $this->_productCollectionFactory->create();
        $collection->addAttributeToSelect('*');
        $collection->addAttributeToFilter('type_id', \Magento\Catalog\Model\Product\Type::TYPE_SIMPLE);
        $collection->getSelect()->order('created_at', \Magento\Framework\DB\Select::SQL_DESC);
        $collection->getSelect()->limit(10);
        return $collection;
    }
}
16
  • @QaiserAliBangash did this re-factored function help you out? If so, please go ahead and mark this answer as accepted so that other readers know that it is valid. Thanks! Oct 21, 2016 at 3:58
  • Thanks for the prompt reply but unfortunately it doesn't work. It returns empty result Oct 21, 2016 at 13:57
  • @QaiserAliBangash If possible, please post your entire class. I want to see what it extends from and I also want to see in your constructor where you declare the product collection factory. There has to be some other problem. Also, have you cleared var/di and var/generation after each change? Is caching enabled or disabled? Are you in developer mode or production mode? These questions will help me fix this for you. Oct 21, 2016 at 14:02
  • Yes i'm in developer mode, have cleared the cache and deleted the var/generation folder. Oct 21, 2016 at 14:20
  • <code><?php namespace Packt\HelloWorld\Block; use Magento\Framework\View\Element\Template; class Newproducts extends Template { private $_productCollectionFactory; public function __construct( Template\Context $context, \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollectionFactory, array $data = []) { $this->_productCollectionFactory = $productCollectionFactory; parent::__construct($context, $data); }</code> Oct 21, 2016 at 14:23
0

I want to share another approach in order to retrieve the last 10 simple products.

You can use ProductRepository with searchCriteria.

<?php

namespace Vendor\ModuleName\Block;

use Magento\Framework\View\Element\Template;

class RecentProduct extends Template
{
    /**
     * @var \Magento\Catalog\Model\ProductRepository
     */
    protected $productRepository;

    /**
     * @var \Magento\Framework\Api\SearchCriteriaBuilder
     */
    protected $searchCriteriaBuilder;

    /**
     * @var \Magento\Framework\Api\FilterBuilder
     */
    protected $filterBuilder;

    /**
     * @var \Magento\Framework\Api\SortOrder
     */
    protected $sortOrder;

    public function __construct(
        \Magento\Framework\View\Element\Template\Context $context,
        \Magento\Catalog\Model\ProductRepository $productRepository,
        \Magento\Framework\Api\SearchCriteriaBuilder $searchCriteriaBuilder,
        \Magento\Framework\Api\FilterBuilder $filterBuilder,
        \Magento\Framework\Api\SortOrder $sortOrder,
        array $data = []
    )
    {
        $this->sortOrder = $productRepository;
        $this->searchCriteriaBuilder = $searchCriteriaBuilder;
        $this->filterBuilder = $filterBuilder;
        $this->sortOrder = $sortOrder;

        parent::__construct($context, $data);
    }

    public function getProducts()
    {
        $this->searchCriteriaBuilder->setCurrentPage(1);
        $this->searchCriteriaBuilder->setPageSize(10);

        $filters[] = $this->filterBuilder
            ->setField('type_id')
            ->setConditionType('eq')
            ->setValue(\Magento\Catalog\Model\Product\Type::TYPE_SIMPLE)
            ->create();
        $this->searchCriteriaBuilder->addFilters($filters);

        $sortOrder = $this->sortOrder->setField('updated_at')->setDirection(SortOrder::SORT_DESC);
        $this->searchCriteriaBuilder->setSortOrders([$sortOrder]);

        return $this->customerRepository->getList($this->searchCriteriaBuilder);
    }
}

Comments:

This code is not tested, but you have the code logic.

This avoid you to use Magento collection directly.

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.