我有一个自定义销售点管理员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;
}
}
?>
Run Code Online (Sandbox Code Playgroud)
如果没有缩略图,整个页面会出错:http: //www.screencast.com/t/zk6jVChiAC
您可以在try catch块中包装触发异常的调用,并将代码放入以执行占位符:
try {
$cMyUrl = $cProduct->getThumbnailUrl();
} catch (Exception $e) {
//Do something here
}
Run Code Online (Sandbox Code Playgroud)
但不要.这只是掩盖了潜在的问题:
/ skin/frontend/your_package/your_theme/images/catalog/product/placeholder和它继承的主题中都缺少占位符图像
你可以看到抛出的异常(和原因:无图像,无占位符)中:app/code/core/Mage/Catalog/Model/Product/Image.php在setBaseFile()方法.
我宁愿让Magento正确处理占位符,而不是让不必要的抛出异常并且必须围绕它编写代码.
因此,将占位符图像添加到上面提到的皮肤图像目录中 - 您应该具有以下内容:
/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
Run Code Online (Sandbox Code Playgroud)
或至少在基本主题中的一些
/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
Run Code Online (Sandbox Code Playgroud)