This ongoing article is meant to be a reference for basic data-fetching tasks in the Mage environment as well as a learn-by-example tutorial. Please add to it as you can...
An extension of Mage_Payment_Model_Method_Abstract (payment module Model) or anywhere with an getOrder() method
Mage_Catalog_Model_Product of an item in the cart
Gets the Mage_Catalog_Model_Product of the first item in the cart...
$item = current( $this->getOrder()->getAllItems() );
$prod = Mage::getModel( 'catalog/product' )
->load( $item->getProductId() );
An “item” is another class altogether and lacks methods for returning a product or accessing things like custom product attributes.
Mage_Catalog_Model_Product
Value of a product’s custom attribute as set by an administrator in the backend
// Take the attributes code (see Manage Attributes in the backend)
// and remove underscores capitalising the next letter. Also
// capitalise the first letter and access as follows:
// Eg. Attribute code: "my_attrib_code"
$myprod->getMyAttribCode();
Mage implements dynamic methods for its (custom) attributes. There are four methods you can use for an attribute: get, set, uns (unset), and has. (see lib/Varien/Object.php, __call() method) To use them, just add the action to the attribute code. For example, using the code “my_attribute_code” - which becomes “MyAttributeCode”, you can call:
Text of a dropdown option selected by an administrator for a custom product or category attribute (i.e. “Text” in <option value=”1”>Text</text>)
// Get the literal value selected
// Load the attribute object
$model_att = Mage::getModel('eav/entity_attribute');
// $att_code is the attribute code string (see Manage Attributes section in the backend)
// substitute 'catalog_product' here for different entity attribs (eg. catalog_category)
$att_id = $model_att->getIdByCode( 'catalog_product', $att_code );
$model_att->load( $att_id );
// Get the literal value
$model_att_options = Mage::getModel('eav/entity_attribute_source_table'); // We get the model handling eav_attribute_option
$model_att_options->setAttribute($model_att); // We set our attribute for this model
// $att_value is the Magento value for the option in the drop down (usually an enumerated integer)
$att_option_text = $model_att_options->getOptionText( $att_val );
Magento assigns enumerated integers for an attribute’s dropdown/select box’s values depending on how many options there are in total and what order they are in on the page, i.e. its a bit arbitrary as the value assigned to each option depends on what order you created the custom attributes. Use this code to get the literal value displayed to the admin user.