我正在尝试创建自定义模块(从权威指南复制粘贴)以在主页上显示随机产品。我开始使用Hello world这很好。但是,当我在主页上显示更多代码以显示产品时,它会给我以下错误。
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
这里是/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;
}
}
任何人都可以告诉我什么是错的。感谢
这里为GetRandomProducts()方法提供了我的代码
<?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;
}
}
答案 0 :(得分:1)
getRandomProducts
模型的Magentotutorial_Definitivehello/Randomproducts
看起来不会返回产品集合。
UPD:
以下是getRandomProduct方法的简化实现:
<?php
public function getRandomProducts($maxCount = 3)
{
$productCollection = Mage::getModel('catalog/product')
->getCollection()
->addAttributeToSelect('*');
$productCollection->getSelect()->order('RAND()')->limit($maxCount);
return $productCollection;
}