Magento 2.1 – Using Factory to Get Product Collection with Product Name

magento-2.1productproduct-collection

I get product collection using \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory in block( dependency injection), the result doesn't have name attribute,

The similar Q&A(ObjectManager) here Product collection has no name attribute how can I get it magento2? doesn't work.

The detail codes is below, my question is "how to add name attribute in the block collection"?


Detail codes

In block:

<?php
namespace Vendor\HelloWorld\Block;
class HelloWorld extends \Magento\Framework\View\Element\Template
{    
    protected $_productCollectionFactory;

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

    public function getProductCollection()
    {
        $collection = $this->_productCollectionFactory->create();
        $collection->addAttributeToSelect('*');
        $collection->setPageSize(3); // fetching only 3 products
        return $collection->getData();
    }
}

In template (.phtml) file:

<?php
$productCollection = $block->getProductCollection();
echo "<pre>";
print_r($productCollection);
echo "</pre>";

Result:

Array
(
    [0] => Array
        (
            [entity_id] => 1
            [attribute_set_id] => 15
            [type_id] => simple
            [sku] => 24-MB01
            [has_options] => 0
            [required_options] => 0
            [created_at] => 2017-08-14 07:07:01
            [updated_at] => 2017-08-14 07:07:01
        )

    ...

)

Best Answer

There are attributes that may not work properly with getData() such as the product price because getData() contains only main table data.

Return full collection object(without getData()) in getProductCollection() function

public function getProductCollection()
{
    $collection = $this->_productCollectionFactory->create();
    $collection->addAttributeToSelect('*');
    $collection->setPageSize(3); // fetching only 3 products
    return $collection;
}

Now you can get product id, name, sku and other information with getter function like getId(), getName(), getSku(), ... in phtml

<?php

$productCollection = $block->getProductCollection();

foreach ($productCollection as $product) {
    echo $product->getId();
    echo $product->getName();
}