根据产品取其自定义属性值

作者:Jeen 发布于:2013-4-21 18:35 Sunday 分类:工作笔记

magento中 使用自定义属性 的频率还是相当高的

之前 自己做模板的时候  再调用产品的某个自定义属性时是绞尽脑汁  也没找到什么好的方法, 因为对程序逻辑本身缺乏基础和认知,所以只能走一些旁门左道,把产品的所有相关属性提取出来后过滤一次,   这样的效率    可想而知
不过这边还是做个简单记录吧:
首先需要一个针对 产品提取 各属性值的 方法, 由于自带的方法包含信息比较多,所以我们需要自己改写 一下
app\code\core\Mage\Catalog\Block\Product\View 目录下的  Attributes.php 文件,参考getAdditionalData 方法,新建改写以下方法
public function getMeSetData($t_product)
{
$data = array();
$product = $t_product;
$attributes = $product->getAttributes();
foreach ($attributes as $attribute) {
$value = $attribute->getFrontend()->getValue($product);

if (!$product->hasData($attribute->getAttributeCode())) {
$value = Mage::helper(‘catalog’)->__(‘N/A’);
} elseif ((string)$value == ”) {
$value = Mage::helper(‘catalog’)->__(‘No’);
} elseif ($attribute->getFrontendInput() == ‘price’ && is_string($value)) {
$value = Mage::app()->getStore()->convertPrice($value, true);
}

if (is_string($value) && strlen($value)) {
$data[$attribute->getAttributeCode()] = array(
‘label’ => $attribute->getStoreLabel(),
‘value’ => $value,
‘code’  => $attribute->getAttributeCode()
);
}
}
return $data;
}
方法有了,接下来就是如何调用了
这边以产品查看页中调用为例:
$p_attrs = Mage::getBlockSingleton(‘catalog/product_view_attributes’)->getMeSetData($_product);
这样取出来的是与产品相关的所有属性信息,再对此属性集过滤  提取自己需要的信息。
foreach($p_attrs as $p_attr => $attr_arr)
{
if(strstr($p_attr,’attr_code’)) {
……. //自定义操作
}
}
这种,一看就是属于吃力不讨好的事,  不过也算是解决问题的一条笨途径了

 

偶然的机会在维护的时候,发现以下代码,简洁明了,具体我没去考证就是了

<?php echo $_product->getResource()->getAttribute(‘attr_code’)->getFrontend()->getValue($_product);

这就是菜鸟与大神间的差距啊 ~~~~…

标签: magento

发表评论:

©2010-2024 Jeen All Rights Reserved.Powered by emlog 京ICP备15058100号-1