I can get the collection, but something is wrong. First, I created a Module to load a product collection:


namespace {Name}\RandProducts\Block;

use Magento\Framework\View\Element\Template;

class Randproductlist extends Template
    private $_productCollectionFactory;
    protected $_logger;

    public function __construct(
       Template\Context $context,
       \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollectionFactory,
       \Psr\Log\LoggerInterface $logger,
       array $data = array()
       parent::__construct($context, $data);
       $this->_productCollectionFactory = $productCollectionFactory;
       $this->_logger = $logger;

    public function getRandomProducts($categoryId) {

        $collection = $this->_productCollectionFactory->create()->load();

        return $collection;

At this point if i go to my phtml in my theme and do:

Random Products

    $productList = $block->getRandomProducts();

    foreach ($productList as $product) {

I can see the sku, and the id but the name is null (and in the backend if i look for the product filter by sku it have name).

But i want to add filters,and, if it's possible, get only 5 random products, so i add in getRandomProducts, before return:

$collection->addAttributeToSelect(['name', 'subtitle', 'image', 'url'])
        ->addAttributeToFilter('status', 1)
        ->addFieldToFilter('is_saleable', '1')

and... nothing works


Replace getRandomProducts following code:

public function getRandomProducts()

    $collection = $this->_productCollectionFactory->create();
    return $collection;

Get random product, try following way:

public function getRandomProducts()

    $collection = $this->_productCollectionFactory->create();
    return $collection;

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.