Find out what I'm doing, Follow Me :)

Wednesday, December 30, 2009

Magento – url functions

Magento had some very handy functions that easily allow you to find some fundamental urls of your site from your phtml files so you can avoid hardcoding them. These are:

    $this->getBaseUrl() - returns the base url of your store (funnily enough)
    $this->getSkinUrl() - returns the url of the folder containing your css, images and local js files (eg skin/frontend/default/your_theme, will vary depending on what package and theme the page is using).
    So to find the image logo.gif in the images folder you would call

    It should be noted that if getSkinUrl does not find the file that you have specified (like images/logo.gif) then it will default to looking in the default theme folders rather than your custom theme folders.

   $this->getJsUrl() - returns the url of the main js folder. So if you want to include a new js library from a template you can use this.

Source :

Tuesday, December 29, 2009

How to add Sitemap to a Magento Site

Most of you must be knowing the importance and use of Sitemaps on your websites, but let me make it clear for those who dont know, how a sitemap helps for the rapid boost of your website. Well, Sitemaps are tree like structure blocks, which can fetch all of your pages and list on one page, for the Search Engines to crawl and index it.

So, in short, it helps mostly for Search Engine Optimization.

If you running an Online Store in Magento, then you may have some problems in getting the Sitemap on a page on your frontend. So, here are some simple steps to get this done.

1. Goto System> Configuration> Catalog> Google Sitemap. Enable all the options in there and make sure, its all correct.

2. Then goto System> Configuration> Catalog> Catalog> Sitemap and enable the Sitemap Creation option.

Now, if you want to add the Sitemap on your header Main Navigation Menu bar, then open this,And there you will find all of your main nav menus listed. Just add a new item to it and link it this way,

<a href="{{store url='catalog/seo_sitemap/category/'}}"> Category Sitemap</a>


<a href="{{store url='catalog/seo_sitemap/product/'}}"> Product Sitemap</a>

I have given two links, as Magento dont have an option to show Product and Category Sitemap both on one single page. So, what you need, just get that active.

And if you want to put the Sitemap link on footer, then just add this above code to your CMS > STATIC BLOCKS> FOOTER LINKS.

Source :

Magento commerce reference and backup posts, installation points

Magento commerce reference and backup posts, installation points.

Since i started to work with magento commerce, i have lost few kilos. Probably this is good weight loss program for me.

From today onward i want to backup the steps, references etc to my blog. I hope this will make me easy to find them easily next time. While i was writing this i looked for the install guide and found this guide on crucial webhost through magento's forum link.

Some of the code helpful to change permission on files and folders while upgrading magento through connect manager.

* Change permission to write
* Through SSH.
chmod o+w var var/.htaccess app/etc
chmod -R o+w media

//or, just change the whole thing writeable for a while
chmod -R 777 staging

//Now change back the permissions
find . -type d -exec chmod 755 {} \;
find . -type f -exec chmod 644 {} \;

Upgrade key to install latest magento:


If the upgrade breaks the magento, try to fix through PEAR using SSH.

./pear install -f --alldeps magento-core/Mage_All_Latest-stable  

Friday, December 25, 2009

How to fix the Magento Out of stock bug, version 1.1.x

This is a popular bug that has been plaguing many people with their custom Magento solutions.

Problem: Magento shows products that are in stock as "Out of Stock" - It seems to be popularly reported within the New Product block.

Solution: The attribute "status" has not been selected in the product collection. This status attribute holds the information about whether or not the product is or is not in stock (among other items that determine if the item should be sale-able).

This attribute needs to be selected via the new product block code.

Find: app/code/core/Mage/Catalog/Block/Product/New.php
You will see:

$products   = $product->setStoreId($storeId)->getCollection()
->addAttributeToFilter('news_from_date', array('date'=>true, 'to'=> $todayDate))
->addAttributeToFilter(array(array('attribute'=>'news_to_date', 'date'=>true, 'from'=>$todayDate), array('attribute'=>'news_to_date', 'is' => new Zend_Db_Expr('null'))),'','left')
->addAttributeToSelect(array('name', 'price', 'small_image'), 'inner')
->addAttributeToSelect(array('special_price', 'special_from_date', 'special_to_date'), 'left')

You need to add: ‘->addAttributeToSelect(’status’);’

$products   = $product->setStoreId($storeId)->getCollection()
->addAttributeToFilter('news_from_date', array('date'=>true, 'to'=> $todayDate))
->addAttributeToFilter(array(array('attribute'=>'news_to_date', 'date'=>true, 'from'=>$todayDate), array('attribute'=>'news_to_date', 'is' => new Zend_Db_Expr('null'))),'','left')
->addAttributeToSelect(array('name', 'price', 'small_image'), 'inner')
->addAttributeToSelect(array('special_price', 'special_from_date', 'special_to_date'), 'left')

Source :

Thursday, December 24, 2009

Adding Tabs in Product View Page – A Magento Way!

It is extremely easy to add a tab and its Javascript, but comparatively difficult to make its CSS, and I won’t talk about that here. You can manage tabs in product page of Magento just through layout files. No need to work on Javascript. Just use the following xml tags inside your catalog_product_view layout.

<block type="catalog/product_view_tabs" name="" as="info_tabs" template="catalog/product/view/tabs.phtml" >
 <action method="addTab" translate="title" module="catalog"><alias>additional</alias><title>General Info</title><block>catalog/product_view_attributes</block><template>catalog/product/view/attributes.phtml</template></action>
 <action method="addTab" translate="title" module="catalog"><alias>deliverytime</alias><title>Delivery Time</title><block>    catalog/product_view</block><template>catalog/product/view/delivery.phtml</template></action>
 <action method="addTab" translate="title" module="catalog"><alias>printinginfo</alias><title>Printing Info</title><block>    catalog/product_view</block><template>catalog/product/view/printing_info.phtml</template></action>
 <!--  4th tab -->
 <action method="addTab" translate="title" module="catalog"><alias>notes</alias><title>Notes</title><block>catalog/product_view</block><template>catalog/product/view/notes.phtml</template></action>

In the code above the fourth tab, we have called addTab method of catalog/product_view_tabs block, with the parameters alias as notes, title as Notes, block as catalog/product_view and template as catalog/product/view/notes.phtml.

After adding this in your layout, echo the following in your view.phtml file.

 echo $this->getChildHtml('');

After that you will see four tabbed navigation in your product view page. Easy isn’t it?

Source :

Wednesday, December 23, 2009

Magento – How to run a SQL query against the database

In order to run a SQL query against the Magento database, you first need a resource model then a database connection.

$db = Mage::getResourceSingleton('core/resource')->getConnection('core_write');
$result = $db->query('SELECT 'entity_id' FROM 'catalog_product_entity');

if(!$result) {
    return FALSE;

$rows = $result->fetch(PDO::FETCH_ASSOC);

if(!$row) {
    return FALSE;


Source :

Tuesday, December 22, 2009

Get all options of select or multiselect attribute in Magento by attribute code

One of the things that a Magento developer deal, time and again is finding out all the options of color or manufacturer or size attribute. You may also need to find out what are the options available for color attribute before you add new option programmatically. Or you may need to add assign the option’s ID to a product. Here’s what you need to do, just load the attribute by attribute code, then load all its options. Easy, isn’t it! Code is below.

     // Add the attribute code here. 
    // Checking if the attribute is either select or multiselect type. 
       // Getting all the sources (options) and print as label-value pair 
       $options = $attribute->getSource()->getAllOptions(false); 
       echo "<pre>"; 

Source :

Monday, December 21, 2009

How to get products from a particular category in magento ecommerce

what I ended up doing is in app/design/frontend/default/theme_name/template/catalog/product/list_random.phtml

doing something like:


$_category = $this->getCurrentCategory();
$subs = $_category->getAllChildren(true);
$result = array();
foreach($subs as $cat_id) {
    $category = new Mage_Catalog_Model_Category();
    $collection = $category->getProductCollection();
    foreach ($collection as $product) {
        $result[] = $product->getId();


this will get you an array of product id's. You can loop through them and create products on the fly using:

foreach ($result as $_product_id){
    $_product = new Mage_Catalog_Model_Product();
    //do something with the product here

then, create a static block in the cms with the following content

{{block type="catalog/navigation" template="catalog/product/list_random.phtml"}}

Finally, in the Catalog->Manage categories section, choose the category, then the display settings tab. Switch the display mode to "Static block and products" and then choose your block from the drop list.

And that should do it.

Source :

Sunday, December 20, 2009

Hide a Category from Magento Category Menu

This is another simple setting that took me a while to figure in the early day of Magento learning. Today someone asked me how to do it thus I’m entering it to our Magento Journal.

To hide a category menu, simply add a new subcategory (e.g: Sales) with following settings:

Is Active: No
Is Anchor: No

Then proceed to adding a new subcategory (e.g: Overstock Deals ) under the “Sales” category you have just created and set:

Is Active: Yes
Is Anchor: Yes

Now you will be able to hide the “Sales” category from the menu, and access “Overstock Deals” somewhere else such as adding a link (Sales) in the footer.

Source :

Friday, December 18, 2009

Magento Quick debugging tip

You can add items to magento’s system log and exception log in your code. This is very handy for pin-pointing coding errors / problems. Developing for Magento is often hard, especially since it’s not always possibly to have error reporting on (and even when it is on, its hard to find exactly what’s wrong!).

Here’s an example of it’s use:

1) Turn on your logging: Admin > Configuration > Developer > Log Settings > Enabled = Yes

2) Example code snippet where you might find this useful:

$response = curl_exec($ch);
//just an example of something - might use this in a custom payment or shipping module


3) Watch your var/log/system.log and var/log/exception.log for raw information from this.

You may run into file permission errors, so you might need to set your folder permissions appropriately

Source :

Thursday, December 17, 2009

Adding images to magento using code (Programmaticaly)

Ive been working on automatically adding products to Magento from a 3rd party XML feed. 

The code to add an image to a product in Magento is:

$product->addImageToMediaGallery($imagePath, array('image','small_image','thumbnail'), false, true, $productData['data_display_name'] . " " . $productData['data_artist_display_name'] . " " . $productData['data_catalog_number']);

It is the array(’image’,’small_image’,'thumbnail’) which tells Magento that you are wanting to use this image as the small image, thumbnail and base image.

Source :

Tuesday, December 15, 2009

Magento eCommerce: How To Reset All Test Order Information and Set Unique Prefix For Orders, Invoices, Shipments, and Credit Memos

A client of ours went in to test products, orders, invoices, etc. to get the feel for the overall "purchase order to shipment
'process from start to finish. After creating many test users, orders, etc. - they now desire to have everything reset back to "0" (zero).

Not only that, but they also want to separate the prefixes for the following items just for ease of dissimilarity when using the Magento ADMIN tools:

    + Orders (set prefix to begin with "1")
    + Invoices (set prefix to begin with "2")
    + Shipments (set prefix to begin with "3")
    + Credit Memo’s (set prefix to begin with "4")
           1. Find "YOUR_DB_NAME" down below and change to match your database name (though leave the ticks ")
           2. Copy and paste code into SQL manager (PhpMyAdmin or similar) and then run the query
           3. Feel free to Create test order, invoice, shipment, and credit memo’s via the ADMIN (easier than going through order process on frontend)
           4. Once you like the changes you see, go back and run the same SQL query
        ...the following will now be in effect:
           + All data pertaining to orders and search terms (Dashboard) are reset to 0 (zero)
           + Order number prefix with 0, Invoice number prefix with 2, Shipment number prefix with 3, Credit Memo number prefix with 4
    Please feel free to copy and paste into your PhpMyAdmin
    -- Reset Magento TEST Data
    -- reset dashboard search queries
    TRUNCATE `catalogsearch_query`;
    ALTER TABLE `catalogsearch_query` AUTO_INCREMENT=1;
    -- reset sales order info
    TRUNCATE `sales_order`;
    TRUNCATE `sales_order_datetime`;
    TRUNCATE `sales_order_decimal`;
    TRUNCATE `sales_order_entity`;
    TRUNCATE `sales_order_entity_datetime`;
    TRUNCATE `sales_order_entity_decimal`;
    TRUNCATE `sales_order_entity_int`;
    TRUNCATE `sales_order_entity_text`;
    TRUNCATE `sales_order_entity_varchar`;
    TRUNCATE `sales_order_int`;
    TRUNCATE `sales_order_text`;
    TRUNCATE `sales_order_varchar`;
    TRUNCATE `sales_flat_quote`;
    TRUNCATE `sales_flat_quote_address`;
    TRUNCATE `sales_flat_quote_address_item`;
    TRUNCATE `sales_flat_quote_item`;
    TRUNCATE `sales_flat_quote_item_option`;
    TRUNCATE `sales_flat_order_item`;
    TRUNCATE `sendfriend_log`;
    TRUNCATE `tag`;
    TRUNCATE `tag_relation`;
    TRUNCATE `tag_summary`;
    TRUNCATE `wishlist`;
    TRUNCATE `log_quote`;
    TRUNCATE `report_event`;
    ALTER TABLE `sales_order` AUTO_INCREMENT=1;
    ALTER TABLE `sales_order_datetime` AUTO_INCREMENT=1;
    ALTER TABLE `sales_order_decimal` AUTO_INCREMENT=1;
    ALTER TABLE `sales_order_entity` AUTO_INCREMENT=1;
    ALTER TABLE `sales_order_entity_datetime` AUTO_INCREMENT=1;
    ALTER TABLE `sales_order_entity_decimal` AUTO_INCREMENT=1;
    ALTER TABLE `sales_order_entity_int` AUTO_INCREMENT=1;
    ALTER TABLE `sales_order_entity_text` AUTO_INCREMENT=1;
    ALTER TABLE `sales_order_entity_varchar` AUTO_INCREMENT=1;
    ALTER TABLE `sales_order_int` AUTO_INCREMENT=1;
    ALTER TABLE `sales_order_text` AUTO_INCREMENT=1;
    ALTER TABLE `sales_order_varchar` AUTO_INCREMENT=1;
    ALTER TABLE `sales_flat_quote` AUTO_INCREMENT=1;
    ALTER TABLE `sales_flat_quote_address` AUTO_INCREMENT=1;
    ALTER TABLE `sales_flat_quote_address_item` AUTO_INCREMENT=1;
    ALTER TABLE `sales_flat_quote_item` AUTO_INCREMENT=1;
    ALTER TABLE `sales_flat_quote_item_option` AUTO_INCREMENT=1;
    ALTER TABLE `sales_flat_order_item` AUTO_INCREMENT=1;
    ALTER TABLE `sendfriend_log` AUTO_INCREMENT=1;
    ALTER TABLE `tag_relation` AUTO_INCREMENT=1;
    ALTER TABLE `tag_summary` AUTO_INCREMENT=1;
    ALTER TABLE `report_event` AUTO_INCREMENT=1;
    -- Reset all ID counters
    TRUNCATE `eav_entity_store`;
    ALTER TABLE  `eav_entity_store` AUTO_INCREMENT=1;
    -- set appropriate prefixes for orders, invoices, shipments, credit memos
    INSERT INTO  `YOUR_DB_NAME`.`eav_entity_store` (`entity_store_id` ,`entity_type_id` ,`store_id` ,`increment_prefix` ,`increment_last_id`) VALUES ('1',  '11',  '1',  '1',  '000000000');
    update `eav_entity_store` set `increment_prefix`= 1 where `entity_type_id`='4' and `store_id`='1';
    update `eav_entity_store` set `increment_last_id`= '000000000' where `entity_type_id`='4' and `store_id`='1';
    INSERT INTO  `YOUR_DB_NAME`.`eav_entity_store` (`entity_store_id` ,`entity_type_id` ,`store_id` ,`increment_prefix` ,`increment_last_id`) VALUES ('2',  '16',  '1',  '2',  '000000000');
    update `eav_entity_store` set `increment_prefix`= 2 where `entity_type_id`='18' and `store_id`='1';
    update `eav_entity_store` set `increment_last_id`= '000000000' where `entity_type_id`='18' and `store_id`='1';
    INSERT INTO  `YOUR_DB_NAME`.`eav_entity_store` (`entity_store_id` ,`entity_type_id` ,`store_id` ,`increment_prefix` ,`increment_last_id`) VALUES ('3',  '19',  '1',  '3',  '000000000');
    update `eav_entity_store` set `increment_prefix`= 3 where `entity_type_id`='24' and `store_id`='1';
    update `eav_entity_store` set `increment_last_id`= '000000000' where `entity_type_id`='24' and `store_id`='1';
    INSERT INTO  `YOUR_DB_NAME`.`eav_entity_store` (`entity_store_id` ,`entity_type_id` ,`store_id` ,`increment_prefix` ,`increment_last_id`) VALUES ('4',  '23',  '1',  '4',  '000000000');
    update `eav_entity_store` set `increment_prefix`= 4 where `entity_type_id`='28' and `store_id`='1';
    update `eav_entity_store` set `increment_last_id`= '000000000' where `entity_type_id`='28' and `store_id`='1';

Source :

Monday, December 14, 2009

How to change or reorder top links?

In the default magento installation, the top links are as follows:

    My Account | My Wishlist | My Cart | Checkout | Log In

In order to change or reorder them you have to do some changes in layout files (xml files).

You can do changes for My Account, Log Out, and Log In from customer.xml file. You can change the title and position of these menu from there.

You can change the ordering of My Cart and Checkout from checkout.xml

See for the following code in checkout.xml

    <action method="addCartLink"></action>
    <action method="addCheckoutLink"></action>

For My Wishlist, open wishlist.xml and search for the following code:

    <action method="addWishlistLink"></action>

Source :

Friday, December 11, 2009

Retrieve products with a specific attribute value

Almost all Magento Models have a corresponding Collection object that can be used to fetch multiple instances of a Model.

To instantiate a Product collection, do the following

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

Products are a Magento EAV style Model, so you'll need to add on any additional attributes that you want to return.

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

//fetch name and orig_price into data

There's multiple syntaxes for setting filters on collections. I always use the verbose one below, but you might want to inspect the Magento source for additional ways the filtering methods can be used.

The following shows how to filter by a range of values (greater than AND less than)

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

//filter for products whose orig_price is greater than (gt) 100

//AND filter for products whose orig_price is greater than (lt) 130

While this will filter by a name that equals one thing OR another.

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

//filter for products who name is equal (eq) to Widget A, or equal (eq) to Widget B
        array('attribute'=>'name','eq'=>'Widget A'),
        array('attribute'=>'name','eq'=>'Widget B'),           

A full list of the supported short conditionals (eq,lt, etc.) can be found in the _getConditionSql method in lib/Varien/Data/Collection/Db.php

Finally, all Magento collections may be iterated over (the base collection class implements on of the the iterator interfaces). This is how you'll grab your products once filters are set.

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

//filter for products who name is equal (eq) to Widget A, or equal (eq) to Widget B
        array('name'=>'orig_price','eq'=>'Widget A'),
        array('name'=>'orig_price','eq'=>'Widget B'),          

foreach ($collection as $product) {

Source :

Thursday, December 10, 2009

How to change Base URL in Magento

Sometimes it may be essential to change the BASE URL of Magento.
(Usually when you want to make a similar copy of Magento on another server!)
There are 2 – 3 simple steps involved in this:

Step 1: Edit old URL values in database

Table: core_config_data

In this table you need to edit the field named value containing specific values in the field named path!
Precisely saying you need to search for web/unsecure/base_url and web/secure/base_url and replace them with new values.

Please refer the images for an example.

OLD Values:

New Values:

Step 2: Login to backend and clear Configuration cache!
This might be simply not possible and hence skip to next step!

Step 3: Find All entries of old domain name in the cache folder and replace them one by one.
Magento retains all configuration cache in /var/cache folder.
This step is  good for Advanced Users who can do file search and replace such strings in one shot
If you are migrating a very big site, then this step will be certainly worth.
I use this “Unix Find Command” very useful in searching:

find . -exec grep -q www.magdummy.cws '{}' \; –print

Step 3: Now it’s time to clear the cache! (Normal User)
As already specified in step2, we know that Magento retains all configuration cache in /var/cache folder.
You can clear the entire contents in this cache folder. Magento regenerates all these files when needed.

Step4: View your new site in the browser.
It should now be working fine like the old one 

I hope this would work fine for you.

Source :

Wednesday, December 9, 2009

Magento Image Upload Problem

Severall people complaint about problems uploading product images at their Magento online shop.After some research we found a solution that i thought it was nice to share with you.

The problem is at servers running Linux / Apache with suhosin configured, it need to be changed from:

suhosin.session.cryptua     On    On


suhosin.session.cryptua     Off    Off

Source :

Tuesday, December 8, 2009

Internal Server Error 500 in Magento

Many of us who started experimenting with this interface and tried to place various values for Base URL, came to a dead end where Magento breaks.  Usually, we get Internal Server Error 500 with each page load. The problem lies in the fact that we can no longer open the Magento administration to correct the error. What needs to be done in such a scenario?

One of our clients wrote me a message today:
I have put in a bad spot. I changed the base URL to {{base_URL}} and now im getting a 500 server error on both the front end and the admin panel. I have looked through the database and cannot find the right field to change this value back. Can you point me in the right direction?

The client went to System> Configuration> Web> Unsecure and placed an invalid value for Base URL field. Beware of this field. Unfortunately, Magento just updates it without any pre-warnings, but change of this specific value can cause Magento to crash.

Usually, we get an error that looks like this:

Internal Server Error

The server encountered an internal error or misconfiguration and was unable to complete your request.

Please contact the server administrator, and inform them of the time the error occurred, and anything you might have done that may have caused the error.

More information about this error may be available in the server error log.

Additionally, a 404 Not Found error was encountered while trying to use an ErrorDocument to handle the request.

The client was on right path to find a solution. We need to open MySQL (usually via php MyAdmin) and find core_config_data table. Once there, manually update 2 rows:

   1. config_id:3 web/unsecure/base_url =>
   2. config_id:4 web/secure/base_url =>

Everything should work now. Hope this will help someone.

Source :

Monday, December 7, 2009

Magento: Displaying Custom Attributes on Product View

Adding custom attributes to your product view is very easy. Adding them to the product listing (category pages) is much more difficult. You’ll need to create a custom module for that. In this post though, I’ll only be showing you how to add attributes to the product view page.

If it is a text field (textbox or textarea), this is all you have to do:

<?php echo $_product->getAttributeName() ?>

There is one thing different here though. If your Attribute Code is “shirt_size”, then you would use getShirtSize(). Remove the underscores and capitalize the first letter of each word. It is picky that way. if you use getshirtsize(), it won’t work.

If you are using a dropdown or a multiple select, you have to call it a little differently:

<?php echo $_product->getAttributeText('shirt_size') ?>

This method requires the actual Attribute Code. If you are displaying the value from a dropdown, you’ll get exactly what you need with this call. If you are wanting to display the values from a multiple select, it will return an array.

Source :

Friday, December 4, 2009

Magento Vertical Category Menu

Magento vertical category menu with the code adapted from this thread. It’s quite easy to implement and to make it even easier for others.

* Add a new block type in "catalog.xml" file
* Create a new phtml file and name it "leftnav.phtml", place it inside catalog/navigation
* Edit CSS

Add a new block type in "catalog.xml" file
Here we presume you want to have the vertical category menu shows up on every page, to do so, we will place the code in the <default> layout like so, and we want it to always stay on the top, so we added "before="-": 
<!-- Mage_Catalog --> 
<reference name="right"> 
<block type="catalog/navigation"before="-" 
name="leftNav" as="leftNav" template="catalog/navigation/leftnav.phtml"/> 

You can change the reference name from ‘right’ to left if you prefer to have the vertical menu placed on the left column. 

Create a leftnav.phtml file
<div class="sidebox"> 
<h6>Browse Category</h6> 
<ul id="side-nav"> 
<?php foreach ($this->getStoreCategories() as $_category): ?> 
<?php if ($_category->getIsActive()) { ?> 
<?php $open = $this->isCategoryActive($_category); ?> 
<?php $potential = $_category->hasChildren(); ?> 
<li class="subcat"><a href="<?php echo $this->getCategoryUrl($_category); ?>"<?php if($open) { echo ' class="open"'; } ?><?php if($potential) { echo ' class="potential"'; } ?> ><?php echo $_category->getName();?></a> 
<?php if ($open && $potential): ?> 
<ul id="sub-sidenav"> 
<?php foreach ($_category->getChildrenCategories() as $subcategory): ?> 
<?php $subCat = Mage::getModel('catalog/category')->load($subcategory); ?> 
<?php $open = $this->isCategoryActive($subCat); ?> 
<?php $potential = $subCat->hasChildren(); ?> 
<li><a href="<?php echo $this->getCategoryUrl($subCat); ?>"<?php if($open) { echo ' class="subopen"'; } ?><?php if(!$potential&&$open) { echo ' class="final"'; } ?> ><?php if($potential&&$open) { echo ' '; } elseif($potential) { echo ' '; }?><?php echo $subCat->getName(); ?></a> 
<?php if ($open && $potential): ?> 
<?php foreach ($subcategory->getChildrenCategories() as $subsubcategory): ?> 
<?php $subsubCat = Mage::getModel('catalog/category')->load($subsubcategory); ?> 
<?php $open = $this->isCategoryActive($subsubCat) ?> 
<li><a href="<?php echo $this->getCategoryUrl($subsubCat); ?>" <?php if($open) { echo ' class="final"'; } ?>><?php echo $subsubCat->getName(); ?></a></li> 
<?php endforeach; ?> 
<?php endif; ?> 
<?php endforeach; ?> 
<?php endif; ?> 
<?php } ?> 
<?php endforeach ?> 

Edit your CSS 
 ul#side-nav li.subcat {background-color:#f5f4f0;border-bottom:1px solid #ddd; 
color:#222;margin: 0 -5px;display: block;} 
ul#side-nav li.subcat a {display: block;padding: 2px 10px;font-size: .85em;} 
ul#side-nav li.subcat:hover { 
background-color:#fefefe;background-position: 50% top;} 
ul#side-nav li.subcat ul li {padding-left:18px; 
line-height: 1.6;background:#fff } 
ul#side-nav li.subcat ul li a {color: #1a443c;font-weight: bold; 
font-size: .85em!important; 
background: url(../images/base_images/icon-arrow-set.png) no-repeat 0 -59px;} 
ul#side-nav li.subcat ul li:hover {text-decoration: underline;} 
ul#side-nav li.subcat a , 
ul#side-nav li.subcat ul li a:hover {text-decoration: none;}

That’s it! Simple isn’t it?
Known issue in Magento version 1.3

The recent release of Magento v1.3 has introduced Flat Catalog Category and Flat Catalog Product features, and some codes had changed in code/core/Mage/Catalog/Naviation.php that resulting Peter’s code not compatible with v1.3, as such, you need to update: 

<?php foreach ($_category->getChildren() as $subcategory): ?>
to <?php foreach ($_category->getChildrenCategories() as $subcategory): ?>

if you wish to switch on Flat Catalog Category; however, we found a bug related to custom options when add to cart is performed with Flat Catalog Category switched on. The bug has been assigned, and before Varien releases an update, your choice is to use the old code with "getChildren" with no Flat Catalog Category enables if you have Configurable products or Simple Products with Custom Options setup. 

The above leftnav code is for Flat Catalog Category switch on. Simply revert "getChildrenCategories()" to "getChildren()" if you do not want to use Flat Catalog Category feature. 

Source :

Thursday, December 3, 2009

Add a footer, Header or Content static callout block for Magento CMS page

Magento offers lots of flexibility for Magento theme design, but it takes a bit of digging and exploring before one can learn to do a new simple trick.

In the Magento default template, it shows us how to place a permanent callout block in the left column by using the

<reference name="left">...</reference>

Example of the code is located in the catalog.xml, right in the <default> section.

<reference name="left">
<block type="core/template" name="left.permanent.callout" template="callouts/left_col.phtml">
<action method="setImgSrc"><src>images/media/col_left_callout.jpg</src></action>
<action method="setImgAlt" translate="alt" module="catalog"><alt>Our customer service is available 24/7. Call us at (800) DEMO-NUMBER.</alt></action>
<action method="setLinkUrl"><url>checkout/cart</url></action>

This is one way of doing it. Though it’s nice, easy and straight-forward, but it lacks the flexibility and the method maybe a bit intimidating to people who know very little about web design and get nervous on touching the source code. So, to make it a bit more friendly for store owner, we can replace the above code to a static block with a block ID, so that store owner can add a new static block in the admin/CMS/Static Block, and can place as many images and content as he sees fit.

How do we do that?
To achieve this, we use the following code instead, and name the block ID as left_column_block. Note that because I wanted this callout block shows up in every page, so I have it placed in the  section just like the example Magento default theme shows.

<reference name="left">
<block type="cms/bock" name="left.permanent.callout ">
<action method="setBlockId"><block_id>left_column_block</block_id></action>

Then I go to admin/CMS/Static Block, add a new block, enter a block title, enter left_column_block as Identifier; enable it, and enter something in the content area. In this example I am using a promotional teaser image file:

<a href="http:/"><img src="" width="206" class="callout" alt="25% off " /> </a>

How about taking it to the next level?
With the same method, we can extend the static block to header, footer and the content area. In the following example, I am going to show you how to do it for the footer block.

To do this, we follow the same step as the left_column_block and reference it to footer; because it’s most logical to have this footer static block shows up throughout the entire site, so I am going to place it in the <default> section in the catalog.xml and I named it footer_callout_block.

<reference name="footer">
<block type="cms/block" name="footer.permanent.callout" as="footer_callout">
<action method="setBlockId"><block_id>footer_callout_block</block_id></action>

One more step before creating a new static block in the admin CMS.

In order for the footer callout block shows up, we need to add a “getChildHtml” to invoke the block in the CMS static block. So we go open up the footer.phtml which is located in the page/html. Note that to have the block shows up exactly where you want it be, requires a bit of CSS coding, but I will skip this part as this is a design decision that you should make, not me. In my example, I have a 2 columns floated layout in the footer, and I want this footer_callout_block placed on the right column, so I have it placed inside the col2 like so:

<div class="col2">
<?php echo $this->getChildHtml('footer_callout') ?>

Then I proceed to the last step by creating a new static block in the admin CMS, and name the following:

Block Title: Footer Callout Block
Identifier: footer_callout_block
Content : <a href=""> <img src="" width="377" alt="ship via USPS and UPS" /> </a>

Source :

Working with AJAX in Magento

Ajax in Magento can be pretty troublesome.Because you will need to take controllers and layout into account.And I almost used up a whole day trying to make ajax work. Here are some of the steps I’d like to share so that you will not waste lots of your time, before making this work.
Let’s first know in Magento terms what we need.

Controller: The url on which Ajax will work on, or the request URL. You will have to set up the controller with its frontend router set in config.xml and its corresponding controller class.
Layout: Layout to handle the requested URL and return HTML if required.
Block: The block to call through layout for the above controller.

Now lets be descriptive.

If you want to show a loader while request is being processed just add the following whereever you like in the phtml page.First fetch the Javascript.

<script src="<?php echo $this->getJsUrl() ?>mage/adminhtml/loader.js" type="text/javascript"></script> 

Then echo the loader which pops up. This loader will be similar to that of the admin.

<div id="loadingmask" style="display: none;"> 
<div class="loader" id="loading-mask-loader"><img src="<?php echo str_replace("index.php/","",$this->getUrl()) ?>skin/adminhtml/default/default/images/ajax-loader-tr.gif" alt="<?php echo $this->__('Loading...') ?>"/><?php echo $this->__('Loading...') ?></div> 
<div id="loading-mask"></div> 

Now to Call Ajax, use the following lines

/*Please note that the URL is created in reloadurl. Also see that the response text will be echoed in div with id=output-div*/ 
var reloadurl = '<?php echo $this->getUrl('router/controller/action') ?>';'loadingmask'); 
new Ajax.Request(reloadurl, { 
method: 'post', 
parameters: "Params_Here", 
onComplete: function(transport) { 
$('output-div').innerHTML = ""; 
$('output-div').innerHTML = transport.responseText; 


After the Ajax Request is made it goes to your controller’s action, which in turn sees to your layout as follows:

class Namespace_module_frontendController extends Mage_Core_Controller_Front_Action  

public function actionAction(){ 


And here is the main part in layout where I spent most of my time in. Since in layout we will have to define reference where the html will echo (Most of the times), i got stuck here, because i need to echo the output on the div with id output-div not in any reference.And the trick is to name the layout as root and output as html. Like the following:

<block type="module/block"  name="root" output="toHtml"  template="module/template.phtml"/> 

You are done now! What ever you write or echo in phtml file you will see populated in the DIV. Now you can treat block as normally as you do before.


Wednesday, December 2, 2009

Add New Reference in Magento

If you already performed some Magento research, you will know that it is built on a fully modular model that gives great scalability and flexibility for your store. While creating a theme, you are provided with many content blocks that you can place in structural blocks.Magento provides few structural blocks by default and many content blocks. This article tells what needs to be in place to create new structural block.

What are structural blocks?
They are the parent blocks of content blocks and serve to position its content blocks within a store page context.These structural blocks exist in the forms of the header area, left column area, right column..etc. which serve to create the visual structure for a store page. Our goal is to create a new structural block called "newreference".

Step 1: Name the structural block

Open the file layout/page.xml in your active theme folder. Inside you will find lines like:

<block type="core/text_list" name="left" as="left"/>
<block type="core/text_list" name="content" as="content"/>
<block type="core/text_list" name="right" as="right"/>

Let’s mimic this and add a new line somewhere inside the same block tag.

<block type="core/text_list" name="newreference" as="newreference"/>

Good. Now we told Magento that new structural block exists with the name "newreference". Magento still doesn’t know what to do with it.

Step 2: Tell Magento where to place it

We now need to point Magento where it should output this new structural block. Let’s go to template/page folder in our active theme folder. You will notice different layouts there. Let’s assume we want the new structural block to appear only on pages that use 2-column layout with right sidebar. In that case we should open 2columns-right.phtml file.

Let’s assume we wish the "newreference" block to be placed below 2 columns, but above the footer. In this case, our updated file could look like this:

<!-- start middle -->
<div>< ?php getChildHtml('breadcrumbs') ?>
<!-- start center -->
<div id="main"><!-- start global messages -->
< ?php  getChildHtml('global_messages') ?>
<!-- end global messages -->
<!-- start content -->
< ?php  getChildHtml('content') ?>
<!-- end content --></div>
<!-- end center -->
<!-- start right -->
<div>< ?php getChildHtml('right') ?></div>
<!-- end right --></div>
<div>< ?php getChildHtml('newreference') ?></div>
<!-- end middle -->

Step 3: Populating structural block

We have the block properly placed, but unfortunately nothing is new on the frontsite. Let’s populate the new block with something. We will put new products block there as an example. Go to appropriate layout XML file and add this block to appropriate place.

<reference name="newreference">
<block type="catalog/product_new" name="" template="catalog/product/new.phtml" />

Source :