0

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

app/code/{Name}/RandProducts/Block/Randproductlist.php
<?php

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();
        $collection->addAttributeToSelect(*);

        return $collection;
    }
}

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

Random Products

<?php
    $productList = $block->getRandomProducts();

    foreach ($productList as $product) {
        var_dump($product->getName());
        var_dump($product->getSku());
        var_dump($product->getId());
    }
?>

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')
        ->getSelect()->orderRand();

and... nothing works

1

Replace getRandomProducts following code:

public function getRandomProducts()
{

    $collection = $this->_productCollectionFactory->create();
    $collection->addAttributeToSelect('*')->load();
    return $collection;
}

Get random product, try following way:

public function getRandomProducts()
{

    $collection = $this->_productCollectionFactory->create();
    $collection->addAttributeToSelect('*');
    $collection->getSelect()->limit(5)->orderRand();
    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.