为Magento网格中的自定义列添加自定义渲染器

redmaomail 2024-07-24 18:13 阅读数 70 #Magento

红帽云邮外贸主机

有时你会需要在Magento的一些网格中添加新列,这是个很简单的任务。但是你可能想按你的方式格式化值或者别的什么。那么写你自己的渲染器就十分有用和简单了。

那么实际情况该如何做呢?让我们看看后台产品列表网格。在/app/code/core/Mage/Adminhtml/Block/Catalog/Product/Grid.php文件中被称为Mage_Adminhtml_Block_Catalog_Product_Grid的类。在这篇文章中我们不重写这个块,但是让你知道如何做到这一点。用新的数据修改_prepareCollection()方法,例如,让我们为一个产品添加短描述。

protected function _prepareCollection()
{
$store = $this->_getStore();
$collection = Mage::getModel('catalog/product')->getCollection()
->addAttributeToSelect('sku')
->addAttributeToSelect('name')
->addAttributeToSelect('short_description') // THIS IS WHAT WE HAVE ADDED
->addAttributeToSelect('attribute_set_id')
->addAttributeToSelect('type_id')
->joinField('qty',
'cataloginventory/stock_item',
'qty',
'product_id=entity_id',
'{{table}}.stock_id=1',
'left');
 
if ($store->getId()) {
//$collection->setStoreId($store->getId());
$collection->addStoreFilter($store);
$collection->joinAttribute('custom_name', 'catalog_product/name', 'entity_id', null, 'inner', $store->getId());
$collection->joinAttribute('status', 'catalog_product/status', 'entity_id', null, 'inner', $store->getId());
$collection->joinAttribute('visibility', 'catalog_product/visibility', 'entity_id', null, 'inner', $store->getId());
$collection->joinAttribute('price', 'catalog_product/price', 'entity_id', null, 'left', $store->getId());
}
else {
$collection->addAttributeToSelect('price');
$collection->addAttributeToSelect('status');
$collection->addAttributeToSelect('visibility');
}
 
$this->setCollection($collection);
 
parent::_prepareCollection();
$this->getCollection()->addWebsiteNamesToResult();
return $this;
}

现在,让我们把这些添加到一个新的列:

*You will find some more code inside this method, but for readability purposes, I'll just say you need to add code you find 

here at beginning of this method...*/
 
protected function _prepareColumns()
{
$this->addColumn('Short description',
array(
'header'=> Mage::helper('catalog')->__('Short description'),
'index' => 'short_description',
'renderer'  => 'Mage_Adminhtml_Block_Catalog_Product_Renderer_Red',// THIS IS WHAT THIS POST IS ALL ABOUT
));
 
}

创建Mage_Adminhtml_Block_Catalog_Product_Renderer_Red 类,其代码如下

< ?php
class Mage_Adminhtml_Block_Catalog_Product_Renderer_Red extends Mage_Adminhtml_Block_Widget_Grid_Column_Renderer_Abstract
{
 
public function render(Varien_Object $row)
{
$value =  $row->getData($this->getColumn()->getIndex());
return '<span style="color:red;">'.$value.'';
 
}
 
}
?>

电商网站开发服务


红帽云邮外贸主机

分享到:
版权声明:本站内容源自互联网,如有内容侵犯了你的权益,请联系删除相关内容。
    红帽云邮外贸主机
热门
    红帽云邮外贸主机
    红帽云邮外贸主机