Category Archives: Magento

All about magento

Adding State for India in Magento

Following SQL code will add Indian state records in directory_country_region and directory_country_region_name tables.

INSERT INTO `directory_country_region` VALUES
(NULL , "IN", "Andaman Nicobar","Andaman Nicobar"),
(NULL , "IN", "Andhra Pradesh","Andhra Pradesh"),
(NULL , "IN", "Arunachal Pradesh","Arunachal Pradesh"),
(NULL , "IN", "Assam","Assam"),
(NULL , "IN", "Bihar","Bihar"),
(NULL , "IN", "Chandigarh","Chandigarh"),
(NULL , "IN", "Chhattisgarh","Chhattisgarh"),
(NULL , "IN", "Dadra Nagar Haveli","Dadra Nagar Haveli"),
(NULL , "IN", "Daman Diu","Daman Diu"),
(NULL , "IN", "Delhi","Delhi"),
(NULL , "IN", "Goa","Goa"),
(NULL , "IN", "Gujarat","Gujarat"),
(NULL , "IN", "Haryana","Haryana"),
(NULL , "IN", "Himachal Pradesh","Himachal Pradesh"),
(NULL , "IN", "Jammu Kashmir","Jammu Kashmir"),
(NULL , "IN", "Jharkhand","Jharkhand"),
(NULL , "IN", "Karnataka","Karnataka"),
(NULL , "IN", "Kerala","Kerala"),
(NULL , "IN", "Lakshadweep","Lakshadweep"),
(NULL , "IN", "Madhya Pradesh","Madhya Pradesh"),
(NULL , "IN", "Maharashtra","Maharashtra"),
(NULL , "IN", "Manipur","Manipur"),
(NULL , "IN", "Meghalaya","Meghalaya"),
(NULL , "IN", "Mizoram","Mizoram"),
(NULL , "IN", "Nagaland","Nagaland"),
(NULL , "IN", "Orissa","Orissa"),
(NULL , "IN", "Pondicherry","Pondicherry"),
(NULL , "IN", "Punjab","Punjab"),
(NULL , "IN", "Rajasthan","Rajasthan"),
(NULL , "IN", "Sikkim","Sikkim"),
(NULL , "IN", "Tamil Nadu","Tamil Nadu"),
(NULL , "IN", "Tripura","Tripura"),
(NULL , "IN", "Uttar Pradesh","Uttar Pradesh"),
(NULL , "IN", "Uttaranchal","Uttaranchal"),
(NULL , "IN", "West Bengal","West Bengal");

INSERT INTO `directory_country_region_name` (`locale` ,`region_id` ,`name` ) 
    SELECT 'en_US', tmp.region_id, tmp.default_name FROM `directory_country_region` 
        AS tmp WHERE tmp.country_id='IN';

Tested on Magento Community Edition Version 1.7

Leave a comment

Posted by on September 3, 2013 in Magento



Add CSS & Js to Magento Layout xml file

Below is the correct way to add css & js files from your theme’s skin and js folder .

  • Add css from theme’s skin in layout xml file-

<action method=”addCss”><stylesheet>css/styles.css</stylesheet></action>


<action method=”addItem”><type>skin_css</type><name>css/menunav1.css</name>

<!– <params/><if>lt IE 8</if> : : (or) <params>media=”print”</params> (optional)–></action>

  • Add js from theme’s skin in layout xml file-

<action method=”addItem”><type>skin_js</type><name>js/js-image-slider.js</name></action>

  • Add js from main root js folder

<action method=”addJs”><script>jquery/jquery-1.8.3.min.js</script></action>

I have tested all above with version 1.7

Leave a comment

Posted by on August 29, 2013 in Magento



Magento Events All About

Note for recent versions of Magento – Broken

Seems like this tutorial doesn’t work anymore for recent versions (1.6.2 for me), because of magento prices indexing. Price is not calculated on the fly on frontend anymore, and indexing does not call the event “catalog_product_get_final_price”. To be confirmed.

It’s confirmed in Issue #25129

Attention: Disable Mage_Compiler

System → Tools → Compilation → In the top right corner there are 2 buttons, make sure the first one is labeled ‘Disabled’.


Apart from the powerful OOP way of customizing Magento, which is overriding methods by subclassing Magento’s core Blocks and Models, there is another way to plug in customizations in key flow areas of your Magento eCommerce shop.

Referred to as the Event-Observer methodology, Magento has been programmed to raise events in crucial areas of the flow Using these events for customizations can keep upgrading a much more simple task that does not require fiddling around with Magento’s core source code. An example would be the event ‘catalog_product_save_after’ which will be raised by Magento immediately after a product is saved.


Event An Event is something that occurs in a certain place during a particular sequence flow. Say once a customer completes an order, the flow sequence would be to

1. Save the order details 2. Send e-mail confirmation to customer

Events may be emitted before or after each of these flow points to introduce custom logic.

Observer An Observer is an event handler. It listens to any event it is attached to and accordingly reacts to the event.

Customization – Using Events vs. Overriding classes

Simply put, think about overriding existing core logic if you need to completely change or if you need to extend core logic and your new logic is going to be reused elsewhere. Use events if you are fine with existing logic provided by Magento and need to add to the core logic.

Example Usage

This example tries to use the Event-Observer technique to introduce a percentage discount for each product. Currently Magento supports special price functionality without a % discount. So we would use this opportunity to customize magento to introduce %discount at a product level.

Before starting, the aim is to ensure that the percentage discount is considered for a simple product when a product is displayed. The event is raised in the class Mage_Catalog_Model_Product_Type_Price→getFinalPrice() (Magento 1.3.0file: app/code/core/Mage/Catalog/Model/Product/Type/Price.php). The event is raised by the line Mage::dispatchEvent(’catalog_product_get_final_price’,array(’product’⇒$product));

The event that we are about to handle is catalog_product_get_final_price which is going to help us add logic to consider the percentage discount.

Step 1

Create a new attribute ‘percent_discount‘.

Attrib Identifier –percent_discount , Scope – Store View , Catalog I/p – Text , Unique Value – No , Values Required – NoInput , Validation –Decimal , Apply to Configurable/All Product Types – Yes

Use in quick search – No , Advanced Search – No , Comparable – No , Visibile on Frontend – Yes , Attribute Label – % Discount

Step 2

Add this new attribute to your attributeset. If your product’s attributeset is ‘default‘, add the new ‘percent_discount’ attribute to this attributeset under “prices” attribute group.

Step 3

Register a new custom local module under name ‘Xyz’. For this create file ‘Xyz.xml’ under directory ‘app/etc/modules/’. File contents are –

  1. <?xml version=”1.0″?>
  2. <config>
  3.   <modules>
  4.     <Xyz_Catalog>
  5.       <codePool>local</codePool>
  6.       <active>true</active>
  7.     </Xyz_Catalog>
  8.   </modules>
  9. </config>

Step 4

Register the event with its Observer. Create file ‘config.xml’ under directory ‘app/code/local/Xyz/Catalog/etc/’ with contents as –

  1. <?xml version=”1.0″?>
  2. <config>
  3.   <global>
  4.     <models>
  5.         <xyzcatalog>
  6.              <class>Xyz_Catalog_Model</class>
  7.         </xyzcatalog>
  8.     </models>
  9.     <events>
  10.       <catalog_product_get_final_price>
  11.         <observers>
  12.           <xyz_catalog_price_observer>
  13.             <type>singleton</type>
  14.             <class>Xyz_Catalog_Model_Price_Observer</class>
  15.             <method>apply_discount_percent</method>
  16.           </xyz_catalog_price_observer>
  17.         </observers>
  18.       </catalog_product_get_final_price>
  19.     </events>
  20.   </global>
  21. </config>

Step 5

Creating the Observer. Create the directory structure – app/code/local/Xyz/Catalog/Model/Price/. Place the php code below in a file by name ‘Observer.php’ in the directory just created.

  1. <?php
  2. class Xyz_Catalog_Model_Price_Observer
  3. {
  4.     public function __construct()
  5.     {
  6.     }
  7.     /**
  8.      * Applies the special price percentage discount
  9.      * @param   Varien_Event_Observer $observer
  10.      * @return  Xyz_Catalog_Model_Price_Observer
  11.      */
  12.     public function apply_discount_percent($observer)
  13.     {
  14.       $event = $observer->getEvent();
  15.       $product = $event->getProduct();
  16.       // process percentage discounts only for simple products
  17.       if ($product->getSuperProduct() && $product->getSuperProduct()->isConfigurable()) {
  18.       } else {
  19.         $percentDiscount = $product->getPercentDiscount();
  20.         if (is_numeric($percentDiscount)) {
  21.           $today = floor(time()/86400)*86400;
  22.           $from = floor(strtotime($product->getSpecialFromDate())/86400)*86400;
  23.           $to = floor(strtotime($product->getSpecialToDate())/86400)*86400;
  24.           if ($product->getSpecialFromDate() && $today < $from) {
  25.           } elseif ($product->getSpecialToDate() && $today > $to) {
  26.           } else {
  27.             $price = $product->getPrice();
  28.             $finalPriceNow = $product->getData(‘final_price’);
  29.             $specialPrice = $price – $price * $percentDiscount / 100;
  30.             // if special price is negative – negate the discount – this may be a mistake in data
  31.             if ($specialPrice < 0)
  32.               $specialPrice = $finalPriceNow;
  33.             if ($specialPrice < $finalPriceNow)
  34.               $product->setFinalPrice($specialPrice); // set the product final price
  35.           }
  36.         }
  37.       }
  38.       return $this;
  39.     }
  40. }

Step 6

NOTE: To get Magento to load the changed local code configuration, one needs to (temporary) disable caching of code configuration. In admin panel, go to System > Cache management and uncheck the Configuration option.

Set the discount on the product. Navigate to the catalog product on the admin login and edit a product. Set the percentage discount for this product (under prices subtab).

Step 7

Navigate to the product details page on the front end and observe that the new discount has taken effect. To be noted here is that, on all other screens where discounted price is required. An example here is the search results screen, where you would need to add this new attribute to the select query search attributes in methodMage_CatalogSearch_Block_Result→_getProductCollection()

  1. $_productCollection= $_productCollection->addAttributeToSelect(‘percent_discount’);

List of Events

The events list is continually expanding in the Magento core and with extensions you can easily add even more events. In v1.4 there are nearly 300 events compared to 223 in v1.3 and 140 in v1.2. On a Unix like system you can easily determine the available events in your particular build by grepping through the Local, Core and Community folders of your install eg change to the Magento root folder and type

  1. grep -rin -B2 -A2 “Mage::dispatchEvent” app/* > events.txt

This will create a file events.txt containing all the events located in the app folder.

If you prefere a shell script check out the blog post on


Other Notes

(From an unknown Wiki user) I found that step 4 was wrong, here is how I got it to work:

Created: local/Company/Module/Model/Observer.php as class Company_Module_Model_Observer

Then I played around with the XML and watched the file it was trying to include (which with the above instructions was looking for classes called Mage_Company). Then I used this XML exactly, changed EVENT_TO_HOOK and ‘Company’ and ‘company’ and ‘module’. Pay attention to case. (Note from the editor: the case of “company_module_model_observer” seems to be wrong. Won’t problably work on case-sensitive file systems).

All above content belongs to Magento WIKI (


Leave a comment

Posted by on August 29, 2013 in Magento



Manipulate Collections in Magento

A collection is a Model type containing other Models, it is basically used in Magento to handle product lists (ie. from a category or a bundle option), but not only.

TO DO: Explain how Magento Implements a collection – Use this to explain how Magento implements a collection by looking at code in a model, so that people can learn to write their own collections.

  1. $collection = Mage::getModel(‘catalog/category’)->load($categoryId)
  2.     ->getProductCollection()
  3.     ->addAttributeToSort(‘name’, ‘ASC’);

To sort using multiple Fields, you can chain calls to the Collection’s method addAttributeToSort(preferred)

  1. $collection = Mage::getModel(‘module/model_name’)->getCollection()
  2.     ->addAttributeToSort(‘order’, ‘ASC’)
  3.     ->addAttributeToSort(‘last_name’, ‘ASC’)
  4.     ->addAttributeToSort(‘first_name’, ‘ASC’)
  5. ;

TODO: use Magento’s API use cases, not Zend_Db_Select ones.

You can also pass IF/THEN statements, but be sure to use the proper quotation of your table’s fields.

  1. $collection = Mage::getModel(‘module/model_name’)->getCollection();
  2. $collection->getSelect()->order( array(‘IF(`order`>0, `order`, 9999) ASC’,
  3.      ‘last_name ASC’, ‘first_name ASC’) );

In this example, the table will be sorted by the order field, then by last name, then by first name, where order is greater than zero, followed by order being equal to or less than zero, all ascending.

Joining Tables

To add SQL joins to a select

  1. $collection = Mage::getModel(‘module/model_name’)->getCollection();
  2. $collection->getSelect()->join( array(‘table_alias’=>$this->getTable(‘module/table_name’)), ‘main_table.foreign_id = table_alias.primary_key’, array(‘table_alias.*’), ‘schema_name_if_different’);

In this example the join method takes an array of alias⇒table_name key pairs, then a standard join clause using `main_table` to refer to the original select, then an array of fields to be retrieved in the join (defaults to *), a different schema can be specified as a last parameter.

→join defaults to an inner join, others can be used:

→joinInner() →joinLeft() →joinRight() →joinFull() →joinCross() →joinNatural()

See lib/Zend/Db/Select.php for source.

Collection Manipulation Methods



addFilter($field, $value, $type = ‘and’)
addItem(Varien_Object $item)
each($obj_method, $args=array())
getCurPage($displacement = 0)
getItemByColumnValue($column, $value)
getItemsByColumnValue($column, $value)
loadData($printQuery = false, $logQuery = false)
load($printQuery = false, $logQuery = false)
setDataToAll($key, $value=null)
setFlag($flag, $value = null)
setOrder($field, $direction = self::SORT_ORDER_DESC)
toArray($arrRequiredFields = array())
walk($callback, array $args=array())



Inherits above methods for Varien_Data_Collection, and in addition (re)defines the following:

addBindParam($name, $value)
addFieldToFilter($field, $condition=null)
addOrder($field, $direction = self::SORT_ORDER_DESC)
initCache($object, $idPrefix, $tags)
loadData($printQuery = false, $logQuery = false)
load($printQuery = false, $logQuery = false)
printLogQuery($printQuery = false, $logQuery = false, $sql = null)
setOrder($field, $direction = self::SORT_ORDER_DESC)
unshiftOrder($field, $direction = self::SORT_ORDER_DESC)

Filter Condition Codes

Attribute Code SQL Equivalent Description
eq =
neq !=
like LIKE
nlike NOT LIKE
in IN ()
nin NOT IN ()
is IS
notnull IS NOT NULL
null IS NULL
moreq >=
gt >
lt <
gteq >=
lteq <=
finset FIND_IN_SET()
from >= for use with dates
to <= for use with dates
date optional flag for use with from/to to specify that comparison value should first be converted to a date
datetime optional flag for use with from/to to specify that comparison value should first be converted to a datetime

If an array is passed but no attribute code specified, it will be interpreted as a group of OR conditions that will be processed in the same way.

If no attribute code is specified, it defaults to eq.


  1. $collection->addAttributeToFilter(‘field_name’, array(
  2.     ‘in’ => array(1, 2, 3),
  3.     ));
  4. $collection->addAttributeToFilter(‘date_field’, array(
  5.    ‘from’ => ‘2000-09-10’,
  6.     ));
  7. $collection->addAttributeToFilter(‘date_field’, array(
  8.     ‘from’ => ’10 September 2000′,
  9.     ‘to’ => ’11 September 2000′,
  10.     ‘date’ => true, // specifies conversion of comparison values
  11.     ));
  12. $collection->addAttributeToFilter(‘field_name’, array(
  13.     ‘notnull’ => true,
  14.     ));
  15. $collection->addAttributeToFilter(‘field_name’, 1); // tests for equality
  16. // Add OR condition:
  17. $collection->addAttributeToFilter(array(
  18.     array(
  19.         ‘attribute’ => ‘field_name’,
  20.         ‘in’        => array(1, 2, 3),
  21.         ),
  22.     array(
  23.         ‘attribute’ => ‘date_field’,
  24.         ‘from’      => ‘2000-09-10’,
  25.         ),
  26.     ));



Inherits above methods for Varien_Data_Collection_Db, and in addition (re)defines the following:

addAttributeToFilter($attribute, $condition=null, $joinType=’inner’) adds WHERE clause on $attribute specified by $condition
addAttributeToSelect($attribute, $joinType=false) gets the value for $attribute in the SELECT clause;
specify * to get all attributes (i.e. to execute SELECT *)
addAttributeToSort($attribute, $dir=’asc’) adds ORDER BY clause on $attribute
addEntityTypeToSelect($entityType, $prefix) doesn’t seem to do anything – don’t use
addExpressionAttributeToSelect($alias, $expression, string|array $attribute) adds SQL expression $expression, using $alias, to SELECT clause (typically containing aggregate functions such as SUM()COUNT());
when $attribute specifies a single attribute as a string, $expression can reference the attribute as simply {{attribute}}, but when passing an array of attributes, each attribute must be referenced in $expression by the name of the specific attribute;
N.B. use with groupByAttribute() when including aggregate functions q.v.
addFieldToFilter($attribute, $condition=null) alias for addAttributeToFilter()
addItem(Varien_Object $object) adds an object to the collection
addStaticField($field) specifies $field as being static, i.e. as existing on the entity table itself, rather than in the EAV table
delete() deletes all entities in the collection
exportToArray() returns collection data as a 2D array
getAllIds($limit=null, $offset=null) returns array of all entity IDs selected by current WHERE clause (optionally specifying $limit and $offset)
getAllIdsSql() not recommended – don’t use
getAttribute($attributeCode) for specified $attributeCode, returnsMage_Eav_Model_Entity_Attribute_Abstract object of the entity object used by the collection (i.e. calls getAttribute($attributeCode) on the entity object and returns the result)
getEntity() returns Mage_Eav_Model_Entity_Abstract object used by collection for attributes
getLoadedIds() returns array of IDs of currently loaded entities
getResource() returns Mage_Core_Model_Resource_Abstract instance;
actually an alias for getEntity() q.v. (an entity is a special type of resource, that is, Mage_Eav_Model_Entity_Abstract extendsMage_Core_Model_Resource_Abstract)
getRowIdFieldName() returns field name of ID attribute for entities in the collection
getTable($table) alias for Mage::getSingleton(‘core/resource’)->getTableName($table)
groupByAttribute($attribute) adds $attribute to GROUP BY clause
importFromArray($arr) imports 2D array into collection as objects
joinAttribute($alias, Mage_Eav_Model_Entity_Attribute_Abstract|string $attribute, string $bind, string $filter=null, string $joinType=’inner’, $storeId=null) joins another entity and adds attribute from joined entity, using $alias, toSELECT clause;
$attribute can specify attribute object, or string in format [entity]/[attribute];
$bind specifies attribute of the main entity on which to make join;
$filter specifies primary key of the joined entity on which to make join (normally defaults to entity_id);
$joinType should be inner or left
joinField($alias, $table, $field, $bind, $cond=null, $joinType=’inner’) joins regular table field using an attribute as foreign key
joinTable($table, $bind, $fields=null, $cond=null, $joinType=’inner’) joins table $table
load($printQuery = false, $logQuery = false) runs query and load data into collection;
specify $printQuery as true to print SQL for debugging
removeAttributeToSelect($attribute=null) removes $attribute from SELECT clause;
specify null to remove all attributes
save() saves all entities in the collection
setEntity(string|object $entity) sets entity object (i.e. Mage_Eav_Model_Entity_Abstract) used by collection for attributes
setObject(Varien_Object $object=null) sets template object for the collection
setOrder(string| $attribute, $dir=’desc’) alias for addAttributeToSort() q.v., identical except that it can accept array of attributes, and default $dir is desc;
N.B. overrides parent function
setPage($pageNum, $pageSize) sets LIMIT clause by specifying page number (one-indexed) and number of records per page;
N.B. equivalent to calling setCurPage($pageNum) andsetPageSize($pageSize) q.q.v.
setRowIdFieldName($fieldName) returns field name of ID attribute for entities in the collection
toArray(array $arrAttributes=array()) calls toArray($attAttributes) on each entity in collection, and returns result as array

ALL above content copied from Magento WIKI..


Posted by on July 23, 2013 in Magento



List all payment methods in Magento

How to get a list with all available payment methods in Magento.

If for any reason you need to a get a list with all payment methods in Magento, you can do it easily by using the payment config class (app/code/core/Mage/Payment/Model/Config.php).

To get a list with all payments active and inactive:

$allAvailablePaymentMethods = Mage::getModel('payment/config')->getAllMethods();

To get a list with all active payment methods:

$allActivePaymentMethods = Mage::getModel('payment/config')->getActiveMethods();

To get a list with all credit cards that Magento supports:

$allCcTypes = Mage::getModel('payment/config')->getCcTypes();
1 Comment

Posted by on July 15, 2013 in Magento



Magento addAttributeToFilter SQL Conditionals

If you want to customize query or product collection data you can easily to do that with addAttributeToFilter funcation in magento. In short you can easily customize product collection select query based on your requirement in magento development.

<?php $collection = Mage::getModel('catalog/product')->getCollection(); ?>

If you want get all fields then use below condition select

<?php $collection->addAttributeToSelect('*'); ?>

If you want to get limited fields then use below condition

<?php $collection->addAttributeToSelect(array('name', 'product_url', 'small_image')); ?>
$collection = Mage::getModel('catalog/product')->getCollection()
   ->addAttributeToSelect(array('name', 'product_url', 'small_image'))
   ->addAttributeToFilter('sku', array('like' => 'test-product%'))

The above code would get a product collection which contain only products that have an SKU starting with “test-product”.

addAttributeToFilter Conditionals

// Is Equal To (eq)
$collection->addAttributeToFilter('status', array('eq' => 1));
// Is Not Equal To (neq)
$collection->addAttributeToFilter('sku', array('neq' => 'test-product'));
// Greater Than (gt)
$collection->addAttributeToFilter('price', array('gt' => 10.05));
// Less Than (lt)
$collection->addAttributeToFilter('price', array('lt' => 15.09));
// Greater Than or Equal To (gteq)
$collection->addAttributeToFilter('price', array('gteq' => 2.29));
// Less Than or Equal To (lteq)
$collection->addAttributeToFilter('price', array('lteq' => 5.44));
// Contains (like) - also uses % wildcards
$collection->addAttributeToFilter('sku', array('like' => 'test-product%'));
// Does Not Contain (nlike) - also uses % wildcards
$collection->addAttributeToFilter('sku', array('nlike' => 'test-product%'));
// In Array (in)
$collection->addAttributeToFilter('id', array('in' => array(1,3,12)));
// Not In Array (nin)
$collection->addAttributeToFilter('id', array('nin' => array(1,2,12)));
// Is NULL (null)
$collection->addAttributeToFilter('description', 'null');
// Is Not NULL (notnull)
$collection->addAttributeToFilter('description', 'notnull');

Debugging The SQL Query
There are two ways to debug the query being executed when loading a collection in Magento.

// Method 1
// Method 2 (Quicker, Recommended)
$collection = Mage::getModel('catalog/product')->getCollection();
echo $collection->getSelect();
Leave a comment

Posted by on July 15, 2013 in Magento



Get order ids filtered by status in Magento

This can be run as a script from the base Magento install folder. If its running inside of a Magento file already (controller or block or whatever) you don’t need the first three lines.


$orders = Mage::getModel('sales/order')->getCollection()
    ->addFieldToFilter('status', 'complete')
   // ->addAttributeToSelect('customer_email')
foreach ($orders as $order) {
    $email = $order->getCustomerEmail();
    echo $email . "\n";


To see all orders with statuses and emails:

$orders = Mage::getModel('sales/order')->getCollection()
    //->addFieldToFilter('status', 'complete')
foreach ($orders as $order) {
    $email = $order->getCustomerEmail();
    echo $order->getId() . ": '" . $order->getStatus() . "', " . $email . "\n";
Leave a comment

Posted by on July 10, 2013 in Magento