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
)
...
)
getData()in foreach $product object in previous question and in this question you usegetData()on whole collection object – Prince Patel Aug 31 '17 at 09:26You have any idea?
– Rajan Soni Jan 11 '18 at 06:58