Get list of product attribute in Magento

# Get list of colors from Magento Installation

Let’s create a file called getcolors.php on Magento root folder.

require_once ( “app/Mage.php” );
Mage::getSingleton(“core/session”, array(“name” => “frontend”));
$attribute = Mage::getSingleton(‘eav/config’)->getAttribute(‘catalog_product’, ‘color’);
if ($attribute->usesSource()) {
$options = $attribute->getSource()->getAllOptions(false);

When you excute the file getcolors.php either from shell or browser, It will print the list of color used in product catalog.



Change a product’s attribute value without loading the entire product model

Loading product in a collection and saving them again and again over will take lot of time. To make it quick there is an alternate solution available which uses the same function used by Update attributes action from the product grid:

->updateAttributes(array($productId), array('attribute_code'=>'value'), 0);



Better way to load layout blocks outside of Magento

For loading Magento Layout Blocks externally or in a controller without any complexity, use this:

From external file, we need to initiate Magento session:

Mage::getSingleton(‘core/session’, array(‘name’=>’frontend’));
$session = Mage::getSingleton(‘customer/session’, array(‘name’=>’frontend’));
$layout = Mage::app()->getLayout();
$top = $layout->getBlock(‘top.links’)->toHtml();
echo $top;

From internal controller:

$layout = Mage::app()->getLayout();
$top = $layout->getBlock(‘top.links’)->toHtml();
echo $top;



Openresty : Programming with Magento/Mysql – Get Inventory of Products REST API

Skills Requried – LUA, nginx, mysql

If you have nginx-openresty installed, open the vhost file of your domain, than follow this:

Let your REST API path is http://<your-domain>.com/getstockserv?p=123450,12145

where p is the parameter where all product ids of Magento Products has been supplied.

Now add this entry to the vhost file –

location ^~ /getstockserv {
content_by_lua ‘
local mysql = require “resty/mysql”;
local cjson = require “cjson”;
args = ngx.req.get_uri_args();
local query = “select product_id from cataloginventory_stock_item where is_in_stock = 0 and product_id in (“.. args.p ..”)”;
local db, err = mysql:new();

local ok, err, errno, sqlstate = db:connect{
host = “<Enter Mysql Hostname>”,
port = 3306,
database = “<Enter Database Name>”,
user = “<Enter Mysql User>”,
password = “<Enter Mysql Password>”,
max_packet_size = 1024 * 1024 };
res, err, errno, sqlstate = db:query(query);
ngx.header[“Content-Type”] = “application/json”;

Reload nginx : nginx -s reload

Voila!! Now you can get the inventory of products without using Magento.



How to add indexer in a Custom Module?

Follow these steps:











Class Module_Model_CmsIndexer extends Mage_Index_Model_Indexer_Abstract


public function getName(){

return ‘Add CMS Cache’;


public function getDescription(){

return ‘Rebuild Cache Index for all CMS Pages’;


protected function _processEvent(Mage_Index_Model_Event $event){

// process


public function reindexAll(){

//Your Function to be executed




Automation, Magento

Automate Magento Image Cache – Don’t let your website down when catalog image cache is flushed!

Clear Catalog Image Cache

No Data Received error after clicking on  Flush Catalog Image Cache

Problem – How to remove Magento Image Cache selectively, when you need to replace existing images and Clicking “Flush Catalog Image Cache” on Magento Cache Management will empty the cache folder which consumes lot of cpu plus memory, and for replacing few images Magento will generate all product images (say for replacing 2 product images it will remove all your 3000 product catalog image cache).

Goal – To Develop an automated solution for removing catalog image cache selectively.

What actually removing Magento catalog image cache does is. it empties the media/catalog/product/cache folder.

Directory where it executes the operation : <Magento Root Directory>/media/catalog/product/cache

Let’s first install a program called ‘incron‘, which is used to monitor modified directories and files and response to the File Events.

– Red Hat / Centos : sudo yum install incron

– Ubuntu / Debian based flavours : sudo apt-get install incron

Turn Service on :

# service incrond start

You also need a script to search / remove the SKU images replaced:

let’s assume you are in /root directory,

# vim

Add Following content on it:

find /<Your Magento Directory>/media/catalog/product/cache/ -name “$1*” -exec rm -f {} \;

save and close it.

Now type the following command to edit your incrontab:

# incrontab -e

<Your Magento Root Directory>/media/catalog/product/cache/<Directory for your Catalog Image (SKU)> IN_CLOSE_WRITE /root/ $#

Example(For SKU’s like KP00234.KP00235):

/var/www/html/media/catalog/product/cache/K/P IN_CLOSE_WRITE /root/ $#

Similarly, for multiple SKU ranges you need to add incrontab rules.
You can check the logs using :

tail -f /var/log/syslog (Centos)

tail -f /var/log/messages (Ubuntu)

Now, you don’t need to worry about cleaning your Catalog Image Cache manually.




Magento Inventory Management – Desktop Tool

Download Magento Desktop Tool allows you to easily manage inventory on your Magento Store.

Magento Inventory Manager


This application allows Store Owners to update product stock on their website. It also allows user to setup a  Gmail(Google) SMTP A/c so that they will get a copy of uploaded stock csv file, which allows them to keep record of stock updation over their store.

Download here.


– Magennto API User.

– Gmail SMTP Settings (Optional).

– Right now it supports CSV with 400 SKU’s maximum at a time.


– Magento Product Inventory Update.

– File Upload Limit

– SMTP Settings for Email Alerts

– Easy to Configure Backend – Secure.

– Stock File Validation Rule( First Line of product stock csv) : sku,qty,is_in_stock






Add an External JS in Magento

To Add an External JS without any problem use this in XML Layout:

[box type=”info”]<reference name="head"><block type="core/text" name="google.cdn.jquery">
<action method="setText"><text><![CDATA[<script type="text/javascript" src=""></script><script type="text/javascript">jQuery.noConflict();</script>]]></text></action></block></reference>

The External JS will be added to the <head> tag.



Magento : Front controller reached 100 router match iterations

Magento Ecommerce In Magento basic urls look like this ‘{name-of-the-module}/{controller}/{action}’ , If the url looks like this ‘{name-of-the-module}/{controller}/’ it’s equivalent to ‘{name-of-the-module}/{controller}/index’ , If the url looks like this ‘{name-of-the-module}/’ it’s equivalent to ‘{name-of-the-module}/index/index’.

For categories and products there is a routing table (core_url_rewrite) in which are saved different rewrite rules in order to have an url like this: /product.html instead of catalog/product/view/id/7869.

This is what happens, internally: you call an url ‘demo-url.html’. Magento looks in the rewrites table for a record with the ‘request_path’ equal to ‘demo-url.html’ in the current store view.  If it’s not found then it searches for a cms page with this identifier and active on the current store view.
If that is not found Magento tries to match it to an url of this form ‘{name-of-the-module}/{controller}/{action}’
if this doesn’t work then you get an error If it finds such a record then if the ‘options’ value is ‘RP’, this means it’s a redirect and you get redirected to the url listed in the ‘target_path’ field else it starts the process all over again with the url from ‘target_path’.
There is a limit of 100 tries. I mean if after 100 tries Magento still finds a record matching the ‘request_path’ you get an internal error ‘Front controller reached 100 router match iterations’

Now for the other part of the url rewrites: how are they saved?

Each time you save a product/category (actually when you save the url key attribute of a product/category) an url rewrite is created. For more details on who this works see Mage_Catalog_Model_Product_Attribute_Backend_Urlkey::beforeSave(); – here the url key is prepared (stripped of illegal characters) The actual saving of the rewrite is done here: Mage_Catalog_Model_Url::refreshProductRewrite() or refreshCategoryRewrite()
What these methods do is to insert records in the core_url_rewrite table with the product/category url_key as ‘request_path’ and ‘catalog/product/view/id/7869’ or ‘catalog/category/view/id/9’ in order to be matched later by the above algorithm.



Zend_Db_Statement_Exception with message ‘SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry’

Exception ‘Zend_Db_Statement_Exception’ with message ‘SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry” while Catalog Url Indexing


Next exception ‘Zend_Db_Statement_Exception’ with message ‘SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry ‘xxxx/xxx/xxx-‘ for key ‘UNQ_CORE_URL_REWRITE_REQUEST_PATH_STORE_ID” in /data/apache/beta/lib/Zend/Db/Statement/Pdo.php:234
Stack trace:


– Find out the request path on Url Rewrites Data, there must be more than single entries for that request path.

– Out of the list  find out the entry whose request_path matches the target_path of any entry in the list.

– Open and Disable the Url Redirection( Set it to No).

– Reindex Catlog Url Indexes, Done.(php -f indexer.php — -reindex catalog_url)



Magento Show Out of Stock Configurable Options – Magento 1.5+

To show Out of Stock options in configurable products, we need to make these changes:

Create a Local Module : Mindgeek_Outofstock

Rewrite /app/code/core/Mage/Catalog/Product/Block/Product/View/Type/Configurable.php


In /app/code/core/Mage/Catalog/Product/Block/Product/View/Type/Configurable.php

class Mindgeek_Outofstock_Block_Product_View_Type_Configurable  extends Mage_Catalog_Block_Product_View_Type_Configurable
//Rewrite getAllowProducts() function:
public function getAllowProducts()
if (!$this->hasAllowProducts()) {
$products = array();
$allProducts = $this->getProduct()->getTypeInstance(true)
->getUsedProducts(null, $this->getProduct());
foreach ($allProducts as $product) {
$products[] = $product;
return $this->getData(‘allow_products’);

Now changes required in design template, view.phtml


<?php if ($_product->isSaleable() && $this->hasOptions()):?>
<?php echo $this->getChildChildHtml(‘container2’, ”, true, true) ?>
<?php endif;?>

<?php if ($this->hasOptions()):?>
<?php echo $this->getChildChildHtml(‘container2’, ”, true, true) ?>
<?php endif;?>

Enable this Module from /app/etc/modules/Mindgeek_Outofstock.xml

<?xml version=”1.0″?>




Disable Magento Visitor Logs – For Better Performance

Disabling Magento Visitor Logs can’t possible from Admin. Disabling Visitor Logs helps in store performance as well as reduces sql queries while surfing the store which decreases MySQL Server load. It also causes Integrity Constraint Error sometimes.

So to disable Visitor logs you need rewrite a Core Model:

/app/code/core/Mage/Log/Model/Visitor.php – Mage_Log_Model_Visitor

Find the below coding in the visitor.php .
protected $_skipRequestLogging = false;

Replace the coding as below and save.
protected $_skipRequestLogging = true;

Save the File and Check your Visitor Log.

[box type=”info”] If you have a high traffic website it is suggested to disable Visitor logs to control the  increasing Database Size.[/box]



Magento Load Related, Upsell and crosssell Products by Ajax using dynamic block creation

To load related products using Ajax just pass current product id by Ajax request and create a controller and add the following code to load the related products:

[box] //Register the Current Magento Product
Mage::register(‘product’, Mage::getModel(‘catalog/product’)->load($productId));
$block = Mage::app()->getLayout()->createBlock(‘catalog/product_list_related’)->setTemplate(‘catalog/product/list/related.phtml’);
$message .= $block->toHTml();
return $message;[/box]



Magento URL Rewrites in a Collection

To Enable Url rewrites while using a Magento collection just add this to the end of collection:


which adds URL rewrites to collection flag



Magento Iphone Theme : Fix Blank Template Error

The following was missing from the top of the page.

Path: app/design/frontend/default/iphone/template/catalog/category

$_helper = $this->helper(‘catalog/output’);
$_product = $this->getProduct();



Magento – Displaying Additional Product Attributes in Catalog List

Firstly I added new method to class Mage_Catalog_Block_Product_View_Attributes:

function setProduct($productId)
if (!Mage::registry('product') && $productId) {
$this->_product = Mage::getModel('catalog/product')->load($productId);

Then I’ve added to /app/design/frontend/*/*/template/catalog/product/list.phtml this:

<table class="info">
$add = new Mage_Catalog_Block_Product_View_Attributes();
$_additional = $add->getAdditionalData();
<?php foreach ($_additional as $_data): ?>
<th><?php echo $_data['label'] ?></th>
<td><?php echo $_data['value'] ?></td>
<?php endforeach; ?>



Magento CONNECT ERROR: Can’t write to file: downloader/.cache/community/

Magento Connect in Magento 1.5 sometimes throws the following error message on attempt to install some extension (we have noticed this on BusinessDecision_Interaktingslider):

CONNECT ERROR: Can't write to file: downloader/.cache/community/BusinessDecision_Interaktingslider-1.0.6/app/code/community/BusinessDecision/Interaktingslider/sql/interaktingslider_setup/mysql4-install-1.0.6.php
You have checked all permissions and sure that the destination is writeable, yet the Magento Connect cannot create this file.
The reason is that function working with archives passing non-ASCII characters in the filename and the filename cannot be created simply due to filesystem restrictions on filenames.
The simple fix can be just patch the _writeFile function indownloader/lib/Mage/Archive/Abstract.php to strip all non-ASCII characters from the filename:
--- Abstract.php
+++ downloader/lib/Mage/Archive/Abstract.php
@@ -43,4 +43,5 @@
     protected function _writeFile($destination, $data)
+        $destination = preg_replace('/[^(\x20-\x7F)]*/','', $destination);
         if(false === file_put_contents($destination, $data)) {
             throw new Mage_Exception("Can't write to file: " . $destination);



Magento redirect simple product to parent configurable product

Add this code in _initProduct() method in IndexController or ProductController in /app/code/core/Catalog/Product/controllers (Create same file in your local folder), which redirects the simple product to parent configurable product.

$configurable_product = Mage::getModel(‘catalog/product_type_configurable’);
$parentIdArray = $configurable_product->getParentIdsByChild($product->getId());

$product = Mage::getModel(‘catalog/product’)->load($parentIdArray[0]);



Linux, Magento

Adding a Cron Job in Magento

Add the following lines to your module’s config.xml file under etc folder.




                <schedule><cron_expr>*/1 * * * *</cron_expr></schedule>








class Namespace_Yourmodulename_Model_Observer {

public static function methodToCall(){

//Code to Execute

Mage::log(“Cron Executed”);




Note: Magento root file cron.php needs to be added to crontab on web server.