Magento: Loading the product from a template
When I wrangle with Magento Commerce and customize anything, every other bit is of course tied to a product's ID, or sometimes entity ID.
The challenging part is that whenever you're in a template in Magento, the scope is very different from the previous one. This is sometimes frustrating, but when you think of it - it makes sense. That is in Magento! ;-)
Magento works in blocks and each block is basically a class file, of course $this is never the same. So for example the scope of a block that renders a product page is different from something like Mage_Sales_Block_Order_Item_Renderer_Default (used to display a row of an order).
I recently had to customize the display of an item in an order in the customer's account.
To do so, I had a nifty helper which is tied to a product's ID. Unfortunately, I was only able to retrieve the SKU, quantity ordered and all sorts of other things right away - but the product's ID was not available.
So how do you load a product otherwise? Simple! Using the SKU!
$sku = $this-getItem()-getSku(); $product = Mage::getModel('catalog/product')-loadByAttribute('sku', $sku); $product-getEntityId(); // here is your ID
So yeah - Mage_Catalog_Model_Product = very helpful. And of course there are a bunch of other attributes to load products by. Well, just about any attribute. Just dig around the docs, or var_dump() a product object on a product page to see what else is available.
Quick and dirty - I just blogged this because it took me 25 minutes to find that model and the loadByAttribute() method.
And hopefully by blogging this, I'll never ever forget.