i am trying to Create a Custom module ( A Copy Paste From Definitive Guide ) to Show random Products on the Home Page. I Started With Hello world It was Fine. But when I added More Code to Show Products On Home Page It Is Giving Me The Following Error.
Fatal error: Call to a member function getName() on a non-object in /opt/lampp/htdocs/magento/app/code/local/Magentotutorial/Definitivehello/Block/Randomproducts.php on line 12
here goes my code for /app/code/local/Magentotutorial/Definitivehello/Block/Randomproducts.php
<?php
class Magentotutorial_Definitivehello_Block_Randomproducts
extends Mage_Core_Block_Template
{
protected function _toHtml()
{
$randProdModel = Mage::getModel('Magentotutorial_Definitivehello/Randomproducts');
$randProducts = $randProdModel->getRandomProducts();
$html = "<ul>";
foreach ($randProducts as $product) {
$name = $product->getName();
$price = number_format($product->getPrice(), 2);
$imageLink = $this->helper('catalog/image')->init($product, 'thumbnail')->resize(100,100);
$productLink = $this->helper('catalog/product')->getProductUrl($product);
$html .= "<p><a href='$productLink'><img src='$imageLink' alt='$name'/></a><br/> $name <br/> $price </p>";
}
$html .= "<ul>";
return $html;
}
}
Can anyone Tell Me Whats Wrong. Thanks
Here Goes My Code For GetRandomProducts() method
<?php
class Magentotutorial_Definitivehello_Model_Randomproducts
extends Mage_Core_Model_Abstract
{
public function getRandomProducts($maxCount = 3)
{
$randProducts = array();
$allProducts = array();
$productCollection = Mage::getModel('catalog/product')
->getCollection()
->addAttributeToSelect('*')
->getItems();
foreach ($productCollection as $id => $data) {
//print_r($data); exit;
$allProducts[] = $data;
}
$productIds = array_keys($allProducts);
$totalProductIds = count($productIds);
for ($i=0; $i<$maxCount; $i++) {
$randIndex = rand(0,$totalProductIds);
$randProductId = $productIds[$randIndex];
$randProducts[] = $allProducts[$randProductId];
}
return $randProducts;
}
}
Looks like getRandomProducts
of Magentotutorial_Definitivehello/Randomproducts
model does not return a product collection.
UPD:
Here is a simplier implementation of the getRandomProduct method:
<?php
public function getRandomProducts($maxCount = 3)
{
$productCollection = Mage::getModel('catalog/product')
->getCollection()
->addAttributeToSelect('*');
$productCollection->getSelect()->order('RAND()')->limit($maxCount);
return $productCollection;
}