odd_duck
odd_duck

Reputation: 4101

Magento - Retrieve custom attribute LABEL in cart with config.xml

I have a custom attribute that i need to display in the shopping cart. The attribute is a Dropdown like so:

Attribute Code : section
Catalog Input Type for Store Owner : Dropdown
Options:
    ID/VALUE = 67 LABEL = warehouse
    ID/VALUE = 69 LABEL = showroom
    ID/VALUE = 70 LABEL = stockroom

To display this i have a custom module with my config.xml like so:

<global>
<sales>
    <quote>
        <item>
            <product_attributes>
                <section/>
            </product_attributes>
        </item>
    </quote>
</sales>

And in the cart i can call:

$_item->getProduct()->getSection();

This returns the ID/VALUE of the attribute (i.e 67) but i want to be able to get the LABEL (i.e warehouse)

I know i can get a label from the id like so:

$_product = Mage::getModel('catalog/product');
$attr = $_product->getResource()->getAttribute("section");
if ($attr->usesSource()) {
    $_label = $attr->getSource()->getOptionText("67");
}

But I want to get the label through my module so i can cutout extra databae queries and having to load the product model again. My cart can have upwards of 20+ items per order so using this last approach can slow it down slightly.

Upvotes: 0

Views: 402

Answers (2)

N0tQuiteMyTemp0
N0tQuiteMyTemp0

Reputation: 1

I assume you have access to Mage_Sales_Model_Quote_Item object. If so, you can try the following snippet:

$_resource = $_item->getProduct()->getResource();
$optionValue = $_resource
    ->getAttributeRawValue($_item->getProduct()->getId(), 'section', Mage::app()->getStore()->getId());
$optionLabel = $_resource
    ->getAttribute('section')
    ->getSource()
    ->getOptionText($optionValue);

Upvotes: 0

fantasticrice
fantasticrice

Reputation: 1621

You can use $_item->getProduct()->getAttributeText('section') instead, which is clearer, but I have not looked into the performance. I would think that if you are loading the products in a collection that includes the attribute already then it will not require separate database calls per product/attribute.

Upvotes: 1

Related Questions