2011-10-21 9 views
0

私はカスタムモジュールを作成しようとしています(確定ガイドからのコピー貼り付け)。私はハローワールドで始まった。しかし、ホームページに商品を表示するためのコードを追加すると、次のエラーが表示されます。致命的なエラー:メンバ関数getName()を呼び出すmagento

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; 
    } 
} 

のための私のコードは、誰もがいただきました間違った私に言うことができる行きます。おかげ

ここではMagentotutorial_Definitivehello/RandomproductsモデルのgetRandomProductsは、製品のコレクションを返さないように私の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; 
    } 
} 
+2

クリスタルボールが壊れている:ここでは

はgetRandomProduct方法のsimplier実装です。コードをアップロードします。 –

答えて

1

が見える行きます。

UPD:

<?php 
public function getRandomProducts($maxCount = 3) 
{ 
    $productCollection = Mage::getModel('catalog/product') 
     ->getCollection() 
     ->addAttributeToSelect('*'); 

    $productCollection->getSelect()->order('RAND()')->limit($maxCount); 

    return $productCollection; 
} 
+0

はい、あなたは正しいですが、時にはうまくいくことがあり、時にはそれは理解できないかもしれません。getRandomProducts()が製品コレクションを返すことがあります。 – ScoRpion

+0

あなたはモデルMagentotutorial_Definitivehello/RandomproductsとメソッドgetRandomProductsの後ろにコードを表示しますか? –

+0

@ Deglin getRandomProducts()のコードを追加しました。それを見てください。 – ScoRpion

関連する問題