1

我有一个自定义的销售点管理员 Magento 扩展。我正在尝试向 POS 页面上的管理产品网格添加缩略图。当每个产品都有缩略图时,它可以 100% 正常工作。但是当有一个没有图像的产品时,代码就完全崩溃了。

如何修改此代码以检查是否有缩略图,如果没有,则显示占位符(任何替代 html 都可以)?

<?php

  class MDN_PointOfSales_Block_Widget_Grid_Column_Renderer_Thumbnail
    extends Mage_Adminhtml_Block_Widget_Grid_Column_Renderer_Abstract
  {
    public function render(Varien_Object $row)
    {      

    $cProduct = Mage::getModel("catalog/product");
    $cProductId = $row->getId();
    $cProduct->load($cProductId);  // works for product IDs w/ a thumbnail. Breaks if no thumbnail set.
    // For example, the following line works, loading the thumbnail for the 5533 product for all rows in the grid:  
    // $cProduct->load(5533);

    $cMyUrl = $cProduct->getThumbnailUrl();

    $html = '<img ';
    $html .= 'src="' . $cMyUrl . '"';
    $html .= 'class="grid-image ' . $cProductId . '"/>';

    return $html;      

    }
  }
?>

如果没有缩略图,整个页面会导致错误: http ://www.screencast.com/t/zk6jVChiAC

4

2 回答 2

7

You could wrap the call that triggers the exception in a try catch block and put code in to do the placeholder:

try {
    $cMyUrl = $cProduct->getThumbnailUrl();
} catch (Exception $e) {
    //Do something here
}

But don't. This is simply masking the underlying problem:

The placeholder image is missing from both /skin/frontend/your_package/your_theme/images/catalog/product/placeholder and the theme it inherits from

You can see the exception being thrown (and the reason: no image and no placeholder) in: app/code/core/Mage/Catalog/Model/Product/Image.php in the setBaseFile() method.

I would rather let Magento handle the placeholders properly, rather than let that exception be thrown unnecessarily and have to code around it.

So, add your placeholder images to the skin images directories mentioned above - you should have the following:

/skin/frontend/your_package/your_theme/images/catalog/product/placeholder/image.jpg
/skin/frontend/your_package/your_theme/images/catalog/product/placeholder/small_image.jpg
/skin/frontend/your_package/your_theme/images/catalog/product/placeholder/thumbnail.jpg

or at least some in the base theme

/skin/frontend/base/default/images/catalog/product/placeholder/image.jpg
/skin/frontend/base/default/images/catalog/product/placeholder/small_image.jpg
/skin/frontend/base/default/images/catalog/product/placeholder/thumbnail.jpg
于 2012-06-06T21:42:13.017 回答
-1

Mage_Catalog_Model_Product_Image::setBaseFile($file) 在目录/图像助手尝试初始化图库并加载缩略图时引发异常。当您尝试获取缩略图 url 时会发生这种情况,而不是在加载产品时。

避免这种情况的最简单方法是使用捕获异常

try {
    $cMyUrl = $cProduct->getThumbnailUrl();
} catch (Exception $e) {
    $cMyUrl = 'default_thumbnail.jpg'; // or something else ;-)
}
于 2012-06-06T21:00:19.580 回答