Is there a simpler way to get an attribute's frontend value?
I have an array of attribute codes which I need to get the values of:
$attributes = array(
'Category' => 'type',
'Manufacturer' => 'brand',
'Title' => 'meta_title',
'Description' => 'description',
'Product Link' => 'url_path',
'Price' => 'price',
'Product-image link' => 'image',
'SKU' => 'sku',
'Stock' => 'qty',
'Condition' => 'condition',
'Shipping cost' => 'delivery_cost');
After iterating through a product collection I get the frontend values of the attributes like so:
$attributeId = Mage::getResourceModel('eav/entity_attribute')
->getIdByCode('catalog_product', $attribute_code);
$attribute = Mage::getModel('catalog/resource_eav_attribute')
->load($attributeId);
$value = $attribute->getFrontend()->getValue($product);
Simply using开发者_JS百科 $product->getDate($attribute)
won't work with dropdowns and multi-selects, it just returns their id and not their frontend value.
While the code above works, it seems to be a long way around getting the value, but more importantly it runs quite slow. Is there a faster/more sensible way to get the frontend values for product attributes?
Edit
I now have the following (after dealing with special cases likeimage
and qty
) which is a bit easier on the eyes and does seem to run quicker (although I don't know why):
$inputType = $product->getResource()
->getAttribute($attribute_code)
->getFrontend()
->getInputType();
switch ($inputType) {
case 'multiselect':
case 'select':
case 'dropdown':
$value = $product->getAttributeText($attribute_code);
if (is_array($value)) {
$value = implode(', ', $value);
}
break;
default:
$value = $product->getData($attribute_code);
break;
}
$attributesRow[] = $value;
If anyone can improve this (make it simpler/more efficient), please post an answer.
For dropdowns and multiselects and only with products (this isn't a general EAV trick) you can use getAttributeText()
.
$value = $product->getAttributeText($attribute_code);
In version 1.7, $product->getAttributeText($attribute_code)
is not working for me on the product page. At first I thought it was because the attribute was not in the catalog_product_flat index. But it turned out that the attribute was there. In any case, the following code works for me. I try the simple code, then fall back on the EAV code.
So I am using code like this:
$value = $product->getAttributeText($attribute_code); // first try the flat table?
if(empty($value) ) { // use the EAV tables only if the flat table doesn't work
$value = $product->getResource()->getAttribute($attribute_code)->getFrontend()->getValue($product);
}
It depends on how you have set up the attribute (is it accessible from the context you are trying to reach it?), but the simplest way is usually like this (for meta_title, for example):
$product->getMetaTitle()
精彩评论