Magento – I can’t get a product attribute value

attributesmodelproductresource-model

I have a Mage_Sales_Model_Order_Shipment_Item object and I'm able to load a product model using the shipment item's sku (if I can get this attribute by just using the shipment item, all the better).

The loaded product model doesn't seem to contain the size attribute. When I var_dump($prod->getData()) or var_dump($prod) there is nothing about its size. The attribute's code is size. It is set on the product I am loading, it is global, Dropdown type, not unique, required. How can I get a specific product attribute, in this case "size", from a model loaded by sku?

$prod = Mage::getModel('catalog/product')->loadByAttribute('sku', $sku);
echo $prod->getSize();
echo $prod->getData('size');

Also, I would expect this to return a value of 57. It is a dropdown type attribute. How can I get the value for this option_id? For example, I'd like to get the value "small", not 57. Btw, I see these values set for this particular sku in the database.

I've tried this solution also

$pc = Mage::getResourceModel('catalog/product_collection')
    ->addAttributeToFilter('size', array('notnull' => 'true'))
    ->addAttributeToFilter('size', array('neq' => ''))
    //->addAttributeToFilter('sku', array('eq' => '100-0055-BLK-S'))
    ->addAttributeToSelect('size');
//$p = $pc->getFirstItem();
$usedAtts = array_unique($pc->getColumnValues('size'));
$attModel = Mage::getSingleton('eav/config')->getAttribute('catalog_product', 'size');
$usedAtts = $attModel->getSource()->getOptionText(implode(',', $usedAtts));
var_dump($usedAtts);

But $usedAtts is false.

Update: I tried the method in my first example, loading the product with sku, on a fresh install and it worked. I setup the size attribute just the same, except the new install has it in the 'default' attribute set, where the prior is a custom. I will try to look into those differences.. but in the meantime, anyone have an idea of why I can't get it in my prior install? I setup the products the same. In the prior, I can get the color attribute.. not sure why I can't get size.

Best Answer

To answer the question:

Thanks to some handy built-in methods you don't have to do any loading on your own:

  • Mage_Sales_Model_Order_Shipment_Item provides getOrderItem
  • Mage_Sales_Model_Order_Item provides getProduct

So, all you should have to do is this:

$product = $shipmentItem->getOrderItem()->getProduct();

If size is persisted to the order item, you can do:

$item = $shipmentItem->getOrderItem();
echo $item->getAttributeText('size');

Or, if you need to load the ID value from the product itself, you can get all of the product's selected ID values:

$size = $shipmentItem->getOrderItem()->getProduct()->getSize();
Related Topic