here is my block file:
path:-Vendor\Module\Block
<?php
namespace Vendor\Module\Block;
class Product 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('*');
return $collection;
}
}
here is my template file:
path:-Vendor\Module\view\frontend\templates
<?php
$collection = $block->getProductCollection();
print_r($collection);
?>
can any one help me with this part?
Thanks in Advance!
My Answer:
In your template file, you are trying to print the collection object directly using print_r(). This will not display the products on the frontend as it will only show the object information.
Instead, you should iterate through the collection and display the products individually. Here is an example of how you can modify your template file to display the products:
php
$collection = $block->getProductCollection();
foreach ($collection as $product) {
echo $product->getName() . "
";
// You can display other product information here
}
?>
This code will loop through each product in the collection and display the product name. You can add more product information as needed. This way, you will be able to see the products on the frontend.
Rate this post
3 of 5 based on 8331 votesComments