Magento 1

Adding Extra Attributes to All Product Collections

This can be very useful for attributes which need to be available on all product collections. This is to be used sparingly, however – adding a lot of attributes to a product collection can drastically impact performance; all attributes should also be indexed into the flat tables so that they’re available when flat catalog is on.




– We add an observer to the catalog_product_collection_load_before event. This will make sure our attributes are added to the collection wherever it’s instantiated from.
– We also add a default node as a placeholder – we’ll allow loaded attributes to be set via the admin’s system configuration.


class Llapgoch_AddProductCollectionAttributes_Model_Observer{
	public function addAttributes($observer){
		$attrs = Mage::helper('llapgoch_addpcattributes')->getAttributesToAdd();
		if(is_array($attrs) && count($attrs)){

– All we need to do is get the attributes we’d like to add to the collection and add them to the select object.


class Llapgoch_AddProductCollectionAttributes_Helper_Data extends Mage_Core_Helper_Abstract{
	const XML_PATH_PRODUCT_ATTRIBUTES = "llapgoch_addpcattributes/general/attributes";
	public function getAttributesToAdd(){
		$attrs = explode(" ", Mage::getStoreConfig(self::XML_PATH_PRODUCT_ATTRIBUTES));
			return $attrs;
		return false;

– We load the attributes which can either be set in the admin area (see System Configuration) or overridden by another module’s config.xml.
– We split the attributes into an array using spaces, but this could be any character.

System Configuration

<?xml version="1.0"?>
		<llapgoch translate="label">
		<llapgoch_addpcattributes translate="label" module="llapgoch_addpcattributes">
			<label>Product Attributes</label>
				<general translate="label">

						<attributes translate="label">
							<label>Collection Attributes To Add</label>
							<comment>Space separate attributes to be added to every product collection</comment>

– We just add our field as a text area to the system config.
– We use a backend model which will be used to warn the user if commas are detected in the string because we’ve chosen to split attributes on spaces.

Backend Model

class Llapgoch_AddProductCollectionAttributes_Model_System_Config_Backend_Attributestring extends Mage_Core_Model_Config_Data{
	public function _afterSave(){
		$helper = Mage::helper('llapgoch_addpcattributes');
		if(strpos($this->getValue(), ",") !== false){
			 Mage::getSingleton('core/session')->addNotice($helper->__('Please use spaces to separate your attribute names instead of commas'));

– Checks the string for the existence of spaces and adds a notice for the user if so.

This code is available as a complete module here:

Magento 1

Emails in Magento: A Guide

Emails in Magento can be incredibly tricky. Firstly, you’ll want to define a field in system config for the template itself; the location of this field dictates the structure of the default node it uses to retrieve available templates and children.

        <rayware translate="label" module="rayware">
        <rayware translate="label" module="rayware">
                <reg_email translate="label">
                    <label>Registration Email</label>
                        <email_template translate="label description" module="rayware">
                            <label>Email Template</label>
                            <description>The template used to send new user reqistrations to rayware</description>

The class adminhtml/system_config_source_email_template finds its default using its own node structure by converting its slashes to underscores, and then looking in global/defaults/template/email so it’ll look here:

            <rayware_reg_email_email_template translate="label" module="rayware">
                <label>[Rayware] New Customer Email</label>

So: The location of system config setting for the email template dictates where the actual template should live in global/template/email node.


The structure of the system config node above dictates where the default should be located. In this instance, it’ll be the following – and the contents of the node should refer to the node name in global/template/email/ above


Sending Emails

$mailTemplate = Mage::getModel('core/email_template');
	'area' => 'frontend',
	 'store' => Mage::app()->getStore()->getId()

$mailTemplate->sendTransactional($templateId, $senderName, $toEmail, $toName, $bind = array(), $storeId = null);
  • Templateid can either be a string or a number, if it’s retrieved from the config then it’ll be worked out automatically if the value has been saved. For the current example, Mage::getStoreConfig(‘rayware/reg_email/email_template’); would be used
  • Sender Name – this refers to one of the transactional sender names in the admin. The name entered here is used to look up a config path in Mage::getStoreConfig(‘trans_email/ident_’ . $sender . ‘/name’);
  • toEmail – the email to send to, this can be an array of email addresses
  • toName – the name of the person to send the email to – this can be an array of names
    bind – array of variables which can be used in the email (See directives)


Define what variables are available in the email using comments at the top of each email file. The subject is also defined in this way.

logo_url and logo_alt are populated from the admin area. The purpose of variables is to allow easy inserting of them from the admin area – this would appear to be their only purpose. The part after the colon is the part which will be shown in the dropdown in the admin (the user friendly name).

<[email protected] Your Quote #{{htmlescape var=$quotation.quote_id}}@-->
<[email protected]
{"store url=\"\"":"Store Url",
"var logo_url":"Email Logo Image Url",
"var logo_alt":"Email Logo Image Alt"}

Email template files live in app/locale/<<country_CODE>>/template/email/ where country code is the code of the country set in the admin area.
The templates can also be placed in en_US, which is the last level of fallback.

Email templates in the database live in the core_email_template table.

Any of the vars can be placed in the subject field using the above, E.g:

<[email protected] {{var title}}@-->



Used to pull out any variables which are passed in to the template via the ‘bind’ parameter. Methods can also be called on passed in variables on the email objects:

{{var subscriber.getConfirmationLink()}}
$bind = array(
    'passedInVariable'  => array(
        'horse' => ‘Moose’


Creates the block, and sets the parameters on them (or calls the methods). If type is not set as a parameter

{{block type=‘cms/block’ customVar=‘1’ methodToCall=‘test’}} 


{{protocol}} -current protocol http or https
{{protocol url=""}} domain URL with current protocol
{{protocol http="http://url" https="https://url"} - also allow additional parameter "store"


{{config path="path/to/config}}


{{customvar code="custom_var_code"}}


{{inlinecss file="path/to/file.css"}}


Loads the layout handle specified and sets all variables on each of the blocks in the layout handle. Methods can also be called on the blocks in the layout handle using this method, if they exist. “area” can also be set as a parameter but will default to the current area if not. Most likely this will be ‘frontend’.

{{layout handle="my_custom_layout_handle_to_be_used" variable="test" method="moose"}}


Embeds the url to a skin asset.

{{skin url="path/to/asset.ext"}}


Embeds a media url.

{{media url="path/to/media/asset.ext"}}


Get the URL for the store. If the url doesn’t end in a suffix, then ‘URL’ can be used, otherwise, direct_url should be used instead. Parameters can also be passed into the url using the syntax _query_paramName=”paramValue”.

{{store url="contacts"}} //
{{store direct_url="html_file.html"}} //
{{store direct_url="goosey.html" _query_param="horseparam"}} // http://dave.magento-test-2.iweb/goosey.html?param=horseparam


Escapes the variable which is passed in from the bind array. certain tags can also be ignored using the allowed_tags parameter

{{htmlescape var="<b>Moose</b>" allowed_tags="b"}} // This would output the moose and keep the bold tags unescaped. See the var directive above for referencing bind params in the same way for htmlescape.
Magento 1


Retrieving the cache object

<?php Mage::app()->getCache();

Checking if a Cache Type is Enabled


Saving to and Retrieving from Cache

Setting $lifetime to 0 or null means the value will be cached indefinitely, alternately enter a second value.

$cache->save($value, $key, $tags = array(), $lifeTime=null);

Clearing a Cache using Tags

<?php $cache->clean($tags = array());

Clearing Cache from the Admin

To clear the custom caches from the admin, use the “Flush Cache Storage” button, as the “Flush Magento Cache” button only deals with Magento’s own cache. Obviously, this is if a custom cache type hasn’t been added to the admin using the method above.

For your custom cache type to appear in the admin, use the following XML to your module’s config file:

             <your_cache_type module="your_module" translate="label description">
                <label>Your Custom Cache Label</label>
                <description>Description of cache type.</description>

Block Caching

To change the caching methods on a block, you can change the cache key to make the block cache for a specific thing. Eg, for a category key:

<?php $block->setCacheKey($category_key);

Or, in XML:

<block type="custom/block" name="custom.block">
    <action method="setCacheKey">
        <!-- or to make it dynamic... -->
        <key helper="myhelper/getCacheKey" />

Turning off Caching for a Block



<action method=”setCacheLifetime” />

Making a Block Cache Permenantly

<?php $block->setCacheLifetime(false);

Magento’s Topmenu

Very few blocks cache by default in Magento, however the Topmenu block is set up to (presumably because of the possibly heavy queries in generating them)

Caching should be set in a block’s constructor if it’s not being set in XML. E.g, The Mage_Page_Block_Html_Topmenu‘s constructor looks like the following:

public function _construct()
        'cache_lifetime' => false,

This behaves the same as $this->setCacheLifetime(false), meaning it will cache indefinitely. A problem with the top menu is that it caches regardless of whether the page is secure or not. If a secure page loads an unsecured cache then any links to elements will cause browser warnings; to get around this, we can do something like the following in the constructor which will create a separate cache of the block for http and https:

$this->addData('cache_key', Mage::app()->getStore()->isCurrentlySecure() ? "secure" : "unsecure");

**TODO: getCacheKeyInfo **

Magento 1

Display Shipping Methods For A Product

This will display appropriate shipping methods on the product detail page

The Block Class

class Namespace_Module_Block_Catalog_Product_Delivery extends Mage_Core_Block_Template{

    protected $_product;

    public function _construct(){

    public function setProductId($productId){
        $this->_product = Mage::getModel('catalog/product')->load($productId);

    public function getDeliveryMethods(){
        $quote = Mage::getModel('sales/quote');
        $existingQuote = Mage::getSingleton('checkout/session')->getQuote();

        if($countryId = $existingQuote->getShippingAddress()->getCountryId()){

        $rates = $quote->getShippingAddress()->getShippingRatesCollection();

       return $rates;

  • Load a new quote object and populate its address with the country of the existing quote or the default config country.
  • Add the product to the quote
  • return the rates

The Template

$_rates = $this->getDeliveryMethods();

<p><?php echo $this->__("DELIVERY OPTIONS");?></p>
<?php if(count($_rates)):?>
    <ul class="product-rates">
    <?php foreach($_rates as $_rate):?>
        <li><?php echo $this->escapeHtml($_rate->getMethodTitle());?></li>
    <?php endforeach; ?>
<?php endif;?>