Magento References

This will probably never be complete, so please help by sending your helpful snippets.

BASE URLS

Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_JS);
//http://magento.demo/js/

Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_LINK);
//http://magento.demo/index.php/

Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_MEDIA);
//http://magento.demo/media/

Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_SKIN);
//http://magento.demo/skin/

Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_WEB);
//http://magento.demo/

// get current url for another store
Mage::getUrl('', array(
    '_current' => true,
    '_use_rewrite' => true,
    '_secure' => true,
    '_store' => $_group->getId(), // the store id (from template/page/switch/stores.phtml)
    '_store_to_url' => true
));
	

MORE URLS

echo $this->getUrl('about');
echo $this->getSkinUrl('images/your-image.jpg');
echo Mage::getDesign()->getSkinUrl('images/your-image.jpg');

URLS in CMS WYSIWYG Editor

{{store url='customer/account'}} 
{{media url='customer/account'}} 
{{skin url='customer/account'}} 

CATEGORIES

Mage::getModel('catalog/category')->load($category_id)->getUrl();
$current_id = Mage::registry('current_category')->getId();

PRODUCT INFO

echo $_product->getShortDescription(); //product's short description
echo $_product->getDescription(); // product's long description
echo $_product->getName(); //product name
echo $_product->getPrice(); //product's regular Price numerically
echo $_product->getSpecialPrice(); //product's special Price numerically
echo $this->getPriceHtml($_product, true); // display product price in html format (template catalog/product/tierprices.phtml)
echo $_product->getProductUrl(); //product url
echo $_product->getImageUrl(); //product's image url
echo $_product->getSmallImageUrl(); //product's small image url
echo $_product->getThumbnailUrl(); //product's thumbnail image url   
echo $_product->getData('attribute_name') ; // check if attribute exists
echo $_product->getAttributeText('attribute'); // output the attribute
echo Mage::getStoreConfig('google/analytics/account') // get any config_data value (this example google analytics code)

CUSTOM ATTRIBUTES

At product level to obtain its value.

echo $_product->getBrandColor(); 

Get attribute collection

$attribute = $_product->getResource()->getAttribute('my_attribute'); 

Get attribute type

$attribute = $_product->getResource()->getAttribute('my_attribute')->getAttributeType(); 

Get attribute Label

$attribute = $_product->getResource()->getAttribute('my_attribute')->getFrontendLabel(); 

Fix the bug in item.phtml where attribute label displays incorrectly:
Replace:

echo $this->htmlEscape($_option['label']); 

With:

echo $this->htmlEscape($_item->getProduct()->getResource()->getAttribute($_option['label'])->getStoreLabel()); 

Fix bug in email/order/items/order/default.phtml where attribute label doesn;t show correctly:

$_productAttribute = $_product->getResource()->getAttribute($option['label']);
echo $_productAttribute->getStoreLabel($_item->getOrder()->getStoreId()); 

Attribute is visible or not

$attribute = $_product->getResource()->getAttribute('my_attribute')->getIsVisible(); 

Attribute is required

$attribute = $_product->getResource()->getAttribute('my_attribute')->getIsRequired();

Get attribute value

$attributeValue = Mage::getModel('catalog/product')->load($_product->getId())->getMyAttribute();

Get the multi-select attribute values

$attributeId = Mage::getResourceModel('eav/entity_attribute')->getIdByCode('catalog_product','attribute_code_here');
$attribute = Mage::getModel('catalog/resource_eav_attribute')->load($attributeId);
$attributeOptions = $attribute ->getSource()->getAllOptions();

Get specific attribute value

$attributeValue = Mage::getModel('catalog/product')
                            ->load($_product->getId())
                            ->getAttributeText('my_attribute');

SNIPPETS

Example usage for images and image title:

$_product = $this->getProduct();
$id = $_product->getId();
$_product_title = $title = $this->htmlEscape($_product->getName());
$_image_file = $_product->getImage();

Get all images from media gallery and do a loop:

<?$_images = Mage::getModel('catalog/product')->load($_product->getId())->getMediaGalleryImages();?>
<?if($_images){?>			
   <?$i=0; foreach($_images as $_image){ $i++;?>
      <a href="#"><img src="<?=$this->helper('catalog/image')->init($_product, 'thumbnail', $_image->getFile())->resize(200, 130); ?>" width="200" height="130" alt="<?=$this->htmlEscape($_image->getLabel());?>" title="<?=$this->htmlEscape($_image->getLabel());?>" /></a>				
   <?}?>
<?}?>

Get the product image for use in transactional emails (e.g.in app/design/frontend/default/template/email/items/order/default.phtml):

$_product = Mage::getModel('catalog/product')->setStoreId($_item->getOrder()->getStoreId())->load($_item->getProductId());
$_product_image_filename = Mage::getModel('catalog/product_media_config')->getMediaUrl($_product->getThumbnail());

Output a static block HTML in template:

echo $this->getLayout()->createBlock('cms/block')->setBlockId('your_block_id')->toHtml(); 

… or in layout XML:

<block type="cms/block" name="your_block_id" before="-">
      <action method="setBlockId"><block_id>your_block_id</block_id></action>
</block>

… or shortcode in admin CMS:

{{block type="cms/block" block_id="your_block_id"}}

Show the actual attribute title on the product options page:

$_attributes = Mage::helper('core')->decorateArray($this->getAllowAttributes());
echo $_attribute->getProductAttribute()->getFrontend()->getLabel();

Check if HTTPS in a template file (useful for adding external sharing services):

<?php if (Mage::app()->getStore()->isCurrentlySecure()): // Check if HTTPS ?>
// Secure HTML code here 
<?php else : ?>
// Insecure HTML code here 
<?php endif; ?>

EXCEPTION LOGS

Mage::log('My log entry');
Mage::log('My log message: '.$myVariable);
Mage::log($myArray);
Mage::log($myObject);
Mage::logException($e);
Mage::log('My log entry', null, 'mylogfile.log');

REQUEST VARIABLES

$this->getRequest() can be used in template (phtml) files or in class files.

// get Controller name
$this->getRequest()->getControllerName();
Mage::app()->getRequest()->getControllerName();
 
// get Action name, i.e. the function inside the controller
$this->getRequest()->getActionName();
Mage::app()->getRequest()->getActionName();
 
//get Router name
$this->getRequest()->getRouteName();
Mage::app()->getRequest()->getRouteName();
 
//get module name
$this->getRequest()->getModuleName();
Mage::app()->getRequest()->getModuleName();

// all
Mage::app()->getRequest();

VALIDATION CODES

'validate-select' - 'Please select an option.'
'required-entry' - 'This is a required field.'
'validate-number' - 'Please enter a valid number in this field.'
'validate-digits' - 'Please use numbers only in this field. please avoid spaces or other characters such as dots or commas.'
'validate-digits-range' - 'The value is not within the specified range.'
'validate-alpha' - 'Please use letters only (a-z or A-Z) in this field.'
'validate-code' - 'Please use only letters (a-z), numbers (0-9) or underscore(_) in this field, first character should be a letter.'
'validate-alphanum' - 'Please use only letters (a-z or A-Z) or numbers (0-9) only in this field. No spaces or other characters are allowed.'
'validate-street' - 'Please use only letters (a-z or A-Z) or numbers (0-9) or spaces and # only in this field.'
'validate-phoneStrict' - 'Please enter a valid phone number. For example (123) 456-7890 or 123-456-7890.'
'validate-phoneLax' - 'Please enter a valid phone number. For example (123) 456-7890 or 123-456-7890.'
'validate-fax' - 'Please enter a valid fax number. For example (123) 456-7890 or 123-456-7890.'
'validate-date' - 'Please enter a valid date.'
'validate-email' - 'Please enter a valid email address. For example johndoe@domain.com.'
'validate-emailSender' - 'Please use only visible characters and spaces.'
'validate-password' - 'Please enter 6 or more characters. Leading or trailing spaces will be ignored.'
'validate-admin-password' - 'Please enter 7 or more characters. Password should contain both numeric and alphabetic characters.'
'validate-cpassword' - 'Please make sure your passwords match.'
'validate-url' - 'Please enter a valid URL. Protocol is required (http://, https:// or ftp://)'
'validate-clean-url' - 'Please enter a valid URL. For example http://www.example.com or www.example.com'
'validate-identifier' - 'Please enter a valid URL Key. For example "example-page", "example-page.html" or "anotherlevel/example-page".'
'validate-xml-identifier' - 'Please enter a valid XML-identifier. For example something_1, block5, id-4.'
'validate-ssn' - 'Please enter a valid social security number. For example 123-45-6789.'
'validate-zip' - 'Please enter a valid zip code. For example 90602 or 90602-1234.'
'validate-zip-international' - 'Please enter a valid zip code.'
'validate-date-au' - 'Please use this date format: dd/mm/yyyy. For example 17/03/2006 for the 17th of March, 2006.'
'validate-currency-dollar' - 'Please enter a valid $ amount. For example $100.00.'
'validate-one-required' - 'Please select one of the above options.'
'validate-one-required-by-name' - 'Please select one of the options.'
'validate-not-negative-number' - 'Please enter a valid number in this field.'
'validate-state' - 'Please select State/Province.'
'validate-new-password' - 'Please enter 6 or more characters. Leading or trailing spaces will be ignored.'
'validate-greater-than-zero' - 'Please enter a number greater than 0 in this field.'
'validate-zero-or-greater' - 'Please enter a number 0 or greater in this field.'
'validate-cc-number' - 'Please enter a valid credit card number.'
'validate-cc-type' - 'Credit card number does not match credit card type.'
'validate-cc-type-select' - 'Card type does not match credit card number.'
'validate-cc-exp' - 'Incorrect credit card expiration date.'
'validate-cc-cvn' - 'Please enter a valid credit card verification number.'
'validate-data' - 'Please use only letters (a-z or A-Z), numbers (0-9) or underscore(_) in this field, first character should be a letter.'
'validate-css-length' - 'Please input a valid CSS-length. For example 100px or 77pt or 20em or .5ex or 50%.'
'validate-percents' - 'Please enter a number lower than 100.'
'required-file' - 'Please select a file'
'validate-cc-ukss' - 'Please enter issue number or start date for switch/solo card type.'

For backend forms:

$fieldset->addField('firled_name', 'select', array(
    'label'=> Mage::helper('adminhtml')->__('FieldName'),
    'class'=> 'required-entry',
    'required'=> true,
    'name'=> 'field_name',
    'values'=> $arrayOfValues
));

In custom templates files:

<input id="inputId" class="required-entry" name="inputName" type="text">

UPGRADE SCRIPTS

update core_resource set version = '0.1.0' where code = 'weblog_setup';

CMS LAYOUT UPDATE

Add this code to the CMS > PAGE DESIGN > Layout Update XML field:

<reference name="root">
<action method="setTemplate">
<template>page/custom_page.phtml</template>
</action>
<action method="setIsHandle">
<applied>1</applied>
</action>
</reference>

COOKIES

/**
 * set cookie
 * name and value are mandatory; other parameters are optional and can be set as null
 * $period = cookie expire date
 */
Mage::getModel('core/cookie')->set($name, $value, $period, $path, $domain, $secure, $httponly);
/**
 * get cookie with a specific name
 * $name = name of the cookie
 */
Mage::getModel('core/cookie')->get($name);
/**
 * get all cookies as an array
 */
Mage::getModel('core/cookie')->get();
/**
 * delete/remove cookie
 * $name is mandatory; other parameters are optional and cen be set as null
 */
Mage::getModel('core/cookie')->delete($name, $path, $domain, $secure, $httponly);

Run cron once on MAMP for testing. Be careful!

/Applications/MAMP/bin/php/php5.3.6/bin/php -f  cron.php

REFERENCES: