Tuesday, December 3, 2013

How to create custom category attribute in Magento

>> If you need to create a category attribute there's no option in magento admin. You need to create it through code or sql. I'm showing the two:

1) Here you can use this code with a new module or create a upgrade sql  for an existing module and write below code by changing your attribute code/Label name.

$installer = $this;

$setup = new Mage_Eav_Model_Entity_Setup('core_setup');

$setup->addAttribute('catalog_category', 'custom_attribute', array(
    'type' => 'int',        // "varchar" for input type text box
    'group'     => 'General Information',
    'backend' => '',
    'frontend' => '',
    'label' => 'Custom Attribute',
    'input' => 'select',    // "text" for input type text box
    'class' => '',
    'source' => 'eav/entity_attribute_source_boolean',            // Leave blank for input type text box
    'global' => Mage_Catalog_Model_Resource_Eav_Attribute::SCOPE_GLOBAL,
    'visible' => true,
    'required' => false,
    'user_defined' => false,
    'default' => '0',        //Leave blank for input type text box
    'searchable' => false,
    'filterable' => false,
    'comparable' => false,
    'visible_on_front' => false,
    'unique' => false,


2)  Or you can run direct sql like this way:

        INSERT INTO `eav_attribute` (`attribute_id`, `entity_type_id`, `attribute_code`, `attribute_model`, `backend_model`, `backend_type`, `backend_table`, `frontend_model`, `frontend_input`, `frontend_label`, `frontend_class`, `source_model`, `is_required`, `is_user_defined`, `default_value`, `is_unique`, `note`) VALUES ('', 3, 'mp3', NULL, '', 'varchar', '', '', 'text', 'Mp3 URL', '', '', 1, 0, '', 0, '');

**** Suppose last inserted ID is 134. This ID will place in the following two table.

        INSERT INTO `eav_entity_attribute` (`entity_attribute_id`, `entity_type_id`, `attribute_set_id`, `attribute_group_id`, `attribute_id`, `sort_order`) VALUES ('', 3, 3, 3, 134, 10);

   Note:- Please check in your database for your attribute type_id , set_id and group_id.

        INSERT INTO `catalog_eav_attribute` (`attribute_id`, `frontend_input_renderer`, `is_global`, `is_visible`, `is_searchable`, `is_filterable`, `is_comparable`, `is_visible_on_front`, `is_html_allowed_on_front`, `is_used_for_price_rules`, `is_filterable_in_search`, `used_in_product_listing`, `used_for_sort_by`, `is_configurable`, `apply_to`, `is_visible_in_advanced_search`, `position`, `is_wysiwyg_enabled`, `is_used_for_promo_rules`) VALUES (134, '', 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, '', 0, 0, 0, 0);

Note* : Will suggest to follow the first step and follow the second to know the table reference.

Friday, November 29, 2013

How to remove State/Region from Estimate Shipping in Magento

If you want to remove the State/Region dropdown from Estimate shipping block. Find the code
new RegionUpdater('country', 'region', 'region_id', <?php echo $this->helper('directory')->getRegionJson() ?>);  and comment out in the app/design/frontend/enterprise/default/template/checkout/cart/shipping.phtml directory

Tuesday, August 13, 2013

Programmatically change product attribute value in a store Magento

>> We have already known that magento has the save() method to save the data through model. We can save a product data programmatically with the product object. Here's a example:

            $_product = Mage::getModel('catalog/product')->load("PRODUCT_ID");
            $_product->setData('name','value');   OR   $_product->setName('value');
            // With this we can change the product name. But the save() method will save globally.

Now suppose you need to change a product visibility for a particular store. Then using this code you can change a particular attribute for a store without saving entire product attributes. Here's it :

            $_product = Mage::getModel('catalog/product')->load("PRODUCT_ID");
            $_product->getResource()->saveAttribute($_product, 'visibility');

Thursday, August 1, 2013

How to use WYSIWYG editor in Admin form field Magento

>> You need to do two small changes. Here's it

    1) open the Edit.php page on your module Yourmodule_Block_Adminhtml_Yourblock_Edit
    Add the method.

     protected function _prepareLayout() {
        if (Mage::getSingleton('cms/wysiwyg_config')->isEnabled()) {

    2) Now open the Form.php change the field you want to change like following:

        $fieldset->addField('description', 'editor', array(
            'name'      => 'description',
            'label'     => Mage::helper('Youmodule')->__('Content'),
            'title'     => Mage::helper('Youmodule')->__('Content'),
            'style'     => 'height:300px; width:700px',
            'config'    => Mage::getSingleton('cms/wysiwyg_config')->getConfig(),
            'wysiwyg'   => true,

            'required'  => false,


Friday, July 26, 2013

Magento :: get static block content mapped with category

>> You can display a static block in a category page by Managing the category from admin.

     But if you want the block in a custom page for that category. You use the following code:

         // load the category
        $_category = Mage::getModel('catalog/category')->load($categoryId);
        // Fetching the block data
        $html = $this->getLayout()->createBlock('cms/block')
        echo $html;

Thursday, July 4, 2013

All categories of a product show in breadcrumbs in magento

>> Here's I've shown how to show all categories of a product in breadcrumbs. It looks like :
      Home / cat1 | Home / cat1 / cat2 | Home / cat3 / Product  You can use a separator before every Home link.
  Edit the file app/code/core/Mage/Catalog/Block/Breadcrumbs.php
 Note* : You must copy the file in your local directory OR override the block before Edit.

Find the method _prepareLayout() and replace with the following code:

        protected function _prepareLayout()
            if ($breadcrumbsBlock = $this->getLayout()->getBlock('breadcrumbs')) {
                /************                Customize for product breadcrumbs            ***********/
                $product = $this->getProduct();
                $categories = $product->getCategoryIds();
                $parentArr = array();
                $childArr = array();
                foreach($categories as $catId){
                    if($catId != 2){
                        $category = Mage::getModel('catalog/category')->load($catId);
                        if(in_array($category->getParentId(),$categories) && $category->getParentId() != 2){
                                $childArr[] = $category->getId();
                                $parentArr[$category->getParentId()] = $childArr;
                                if($parentArr[$category->getParentId()] == '') $childArr = array();
                                $parentArr[$category->getParentId()] = $childArr;
                            $parentArr[$category->getId()] = '';
                foreach($parentArr as $pId => $cArr){
                    $cat = Mage::getModel('catalog/category')->load($pId);
                    $firstClass = ($i++ == 0) ? $cat->getId().' first' : $cat->getId();
                    $breadcrumbsBlock->addCrumb('home product '.$firstClass, array('label'=>Mage::helper('core')->__('Home'),
                                                'title'=>Mage::helper('core')->__('Home Page'), 'link'=>Mage::getBaseUrl()));
                    $breadcrumbsBlock->addCrumb(strtolower(str_replace(' ','_',$cat->getName())), array('label'=> $cat->getName(),
                                                    'title'=> $cat->getName(), 'link'=> $cat->getUrl()));
                    foreach($cArr as $cId){
                        $child = Mage::getModel('catalog/category')->load($cId);
                        $breadcrumbsBlock->addCrumb('home product '.$cId.$cat->getId(), array('label'=>Mage::helper('core')->__('Home'),
                                                    'title'=>Mage::helper('core')->__('Home Page'), 'link'=>Mage::getBaseUrl()));
                        $breadcrumbsBlock->addCrumb(strtolower(str_replace(' ','_',$cat->getName())).$cId, array('label'=> $cat->getName(),
                                                        'title'=> $cat->getName(), 'link'=> $cat->getUrl()));
                        $breadcrumbsBlock->addCrumb(strtolower(str_replace(' ','_',$child->getName())), array('label'=> $child->getName(),
                                                    'title'=> $child->getName(), 'link'=> $child->getUrl()));
                if(count($parentArr) == 0){
                    $breadcrumbsBlock->addCrumb('home product first', array('label'=>Mage::helper('core')->__('Home'),
                                                'title'=>Mage::helper('core')->__('Home Page'), 'link'=>Mage::getBaseUrl()));
                $breadcrumbsBlock->addCrumb('prod'.$product->getId(), array('label'=> $product->getName(), 'title'=> $product->getName(), 'link'=> ''));
                /***********            Customize for product breadcrumbsBlock    END            *************/
            return parent::_prepareLayout();

Thursday, June 27, 2013

how to redirect referer page after login in magento

>> Only admin setting (step 1) needed to redirect customer after login. Using this I'm showing how will you restrict a page only for registered customer. If someone click the url www.example.com/restricted_page.html, it'll redirect to login page. Then after login it should redirect back to the www.example.com/restricted_page.html.
Here's how I did it :

    Step 1: Go to Admin => System => Configuration => Customer Configuration => Login Options => "Redirect Customer to Account Dashboard after Logging in" set it "No".
    Step 2: If you're using a module page then you've the controller Action method like:
            public function indexAction()
                // use here to restrict the page //
                    Mage::getSingleton('customer/session')->setBeforeAuthUrl('Restricted Page Url');
                //        End your addition //

            you can use one of this code to redirect:
            Mage::getSingleton('customer/session')->setBeforeAuthUrl('Restricted Page Url');
            $this->_redirect('customer/account/login/referer/'.Mage::helper('core')->urlEncode('Restricted Page Url'));
    Step 3: (optional) If you're using a cms page then follow this step:
            In your admin CMS section include a phtml page and write the below code at the top of the page:
                Mage::getSingleton('customer/session')->setBeforeAuthUrl('Restricted Page Url');
>> Now if you want to use the login url inside a page with referer url follow this:
    <?php $referer = Mage::helper('core')->urlEncode(Mage::helper('core/url')->getCurrentUrl()); ?>
    <a href="<?php echo Mage::getUrl('customer/account/login', array('referer' => $referer)) ?>">Login</a>

Monday, June 24, 2013

How to add multi-select attribute in Admin product Grid view

Here I've shown a multi-select attribute named "brand".

>> In admin Grid.php find the method "_prepareColumns()" add the following code:

        $attribute = Mage::getModel('eav/config')->getAttribute('catalog_product', 'brand');        // attribute code here
        foreach ( $attribute->getSource()->getAllOptions(true, true) as $option)
            if($option['value'] != '')
            $valArr[$option['value']] =  $option['label'];
        // above code will use to show the dropdown
                'header'=> Mage::helper('catalog')->__('Brands'),
                'width' => '60px',
                'index' => 'brand',
                'type'  => 'options',
                'options' => $valArr,
                'renderer'  => 'Mage_Adminhtml_Block_Catalog_Product_Renderer_Brands', // Will have to create the renderer.
                'filter_condition_callback' => array($this, '_filterBrandCondition')
        Then in this page you need to define the method "_filterBrandCondition" to filter with selected item.
        protected function _filterBrandCondition($collection, $column)
            if (!$value = $column->getFilter()->getValue()) {
            $this->getCollection()->addFieldToFilter('brand', array('finset' => $value));
>> Now create the Brands.php file in code/local/Mage/Adminhtml/Block/Catalog/Product/Renderer directory and use the following code:

        class Mage_Adminhtml_Block_Catalog_Product_Renderer_Brands extends Mage_Adminhtml_Block_Widget_Grid_Column_Renderer_Abstract
            public function render(Varien_Object $row)
                $brands = explode(',',$row->getBrand());
                $html = "";
                    $html ="<ul>";
                    foreach($brands as $value)
                        $_productModel = Mage::getModel('catalog/product');
                        $attribute = $_productModel->getResource()->getAttribute("brand");
                        if ($attribute ->usesSource()) {
                            $html .= "<li>".$attribute ->getSource()->getOptionText("$value")."</li>";
                    $html .= "</ul>";
                return $html ;
 cheer :-)

Wednesday, May 29, 2013

Add extra cost to every shipping method in Magento

>>  I needed to add extra cost to every shipping method price. There would be any other better way to do it but I did the following :

         Open the Rate.php file within app/code/core/Mage/Sales/Model/Quote/Address directory. Find this method:
    public function importShippingRate(Mage_Shipping_Model_Rate_Result_Abstract $rate)
        if ($rate instanceof Mage_Shipping_Model_Rate_Result_Error) {
        } elseif ($rate instanceof Mage_Shipping_Model_Rate_Result_Method) {
        return $this;

    Add extra 10 price with $rate->getPrice() like :  

  Note: Editing the core file is not a good practice. If anyone find any other solution, please must share with me. :)

Monday, April 29, 2013

Import dump data to mysql through command promt

>> Mysql import from CSV :

      > mysqlimport --fields-terminated-by=, --fields-enclosed-by="\"" --lines-terminated-by="\r\n" DBNAME FILEPATH -u USERNAME -p --columns=code,city,state,county

Thursday, April 18, 2013

How to get all subcategories of a category in Magento

 >> Suppose you need to get the list of all subcategory of "cat1" (id : 10)

       $category = Mage::getModel('catalog/category')->load(10); // load the parent category
    There are many way to do it. I'll show you the two :
    1. $subcatCollection = Mage::getModel('catalog/category')->getCollection()
                ->addAttributeToFilter('parent_id',array('eq' => 10));
       // This will return the subcategory collection.
   2. $subcategories = $category->getChildren();
       // This will return all subcategory id with comma separator like : 11,12,13

Thursday, April 11, 2013

How to show review block on product page in Magento

>> To get the review block in product details page. You need to follow the two steps:

       1) Add this code to catalog.xml like:
            <catalog_product_view translate="label">
                <reference name="content">
                    <block type="catalog/product_view" name="product.info" template="catalog/product/view.phtml">
                            <!--You need to copy below section -->
                        <block type="page/html_pager" name="product_review_list.toolbar"/>
                        <block type="core/template" name="product_review_list.count" template="review/product/view/count.phtml" />
                        <block type="review/product_view_list" name="product.detail.info.product_additional_data" as="product_review_data" template="review/product/view/list.phtml">
                            <block type="review/form" name="product.review.form" as="review_form">
                                <block type="page/html_wrapper" name="product.review.form.fields.before" as="form_fields_before" translate="label">
                                    <label>Review Form Fields Before</label>
                                    <action method="setMayBeInvisible"><value>1</value></action>
                            <!--        END            -->

       2) Now go to the view.phtml page. here you need to add this code:
               <?php echo $this->getChildHtml('product_review_data') ?>
            you are done> :)
>> To change the default number of reviews shown per page, follow this:

        By default it shows 10, 20, 50. Go to app/code/core/Mage/Page/Block/Html/Pager.php
        there you can find the line 
            <?php protected $_availableLimit = array(10=>10,20=>20,50=>50);  ?>
        change it as you want        
            <?php protected $_availableLimit = array(5=>5,10=>10,50=>50);  ?>
   Note*: You should do this step either by overriding the block OR copy the same file in the local directory like:  app/code/local/Mage/Page/Block/Html/Pager.php

Friday, March 29, 2013

Custom error/success message in Magento

>> A simple and most needed thing that we frequently use in Magento that how to add custom Error and Success message in Controller page.

You just need to call these methods:
$session = Mage::getSingleton('core/session');  
// You can specify the session with yours like:  
// Mage::getSingleton('customer/session'),
// Mage::getSingleton('checkout/session')

$session->addSuccess('your message here');
$session->addError('your message here');

Tuesday, March 26, 2013

Special character of Regular Expression

Regular Expression :

>> Meaning of Special character [](){}|?+-*^$\

    []    => Square brackets can be used to define a character group. [abc] The example finds one of the characters a, b or c.   

    -    => The hyphen can be used to define a range of characters. [a-f] The example finds one of the characters a, b, c, d, e or f. Also in this example, the regular expression only matches one character.

    ^    => With the meta character ^ at the beginning of a character group, the character group is negated. That means, the example will match any character but not an a. [^a]

           ^a If the meta character ^ is not included into a character group, it stands for the beginning of a string or a line. The example would match all lines or strings beginning with a.

    $    => a$ Like the meta character ^ stands for the beginning of a string or a line, the character $ stands for its end. The example would match all strings or lines ending with an a.
            ^abc$ Here the meta characters ^ and $ are used together. This example would match all strings or lines which are equal to "abc".
            Example 1: abc
            Example 2: abc abc

Friday, March 22, 2013

Prevent visitors to view the store without login in Magento

>> Magento use methods :  _redirect() AND _redirectUrl()
for redirect in Mage_Core_Controller_Varien_Action controller. If you see these methods, they are using this code to redirect $this->getResponse()->setRedirect('your_url');

Now you just need to call like :

I used this code to prevent visitors to view my store without login.
With the following code in head.phtml :

    $frontController = Mage::app()->getFrontController();
    if(!$CusSession->isLoggedIn() && $frontController->getRequest()->getActionName() != 'login')

Wednesday, February 20, 2013

How to add image in magento admin product Grid

>> With the help of this code you can able to add product image in admin Grid View :

    Step 1:
    First you need to copy the core block to local. Copy Grid.php from app/code/core/Mage/Adminhtml/Block/Catalog/Product/Grid.php to
    Here you'll find a method named _prepareColumns(), add the below code within this method
        $this->addColumn('product_image', array(
              'header'    => Mage::helper('catalog')->__('Image'),
              'align'     =>'left',
              'index'     => 'entity_id',
              'width'     => '100px',
              'renderer'  => 'Mage_Adminhtml_Block_Catalog_Product_Renderer_Image'

    Step 2:
    Now create the renderer file named Image.php in the following path
    Here add the below code..
    class Mage_Adminhtml_Block_Catalog_Product_Renderer_Image extends Mage_Adminhtml_Block_Widget_Grid_Column_Renderer_Abstract
        public function render(Varien_Object $row)
            $_product = Mage::getModel('catalog/product')->load($row->getEntityId());
            if($_product->getImage() != 'no_selection'){
                  $image = "<img src='".Mage::helper('catalog/image')->init($_product, 'image')->resize(100)."' title='".$_product->getName()."' />";
            return $image;


Tuesday, February 19, 2013

Use INR symbol in magento

 >> By default magento shows indian rupee as "Rs". If you want to show the symbol.

        &#8377; = ₹
        &#8360; = ₨

      i.e.  &#8377; 1,200 would show ₹ 1,200

     Note* : Use the font DejaVu Sans <span style='font-family: DejaVu Sans;'>&#8377;</span> for Internet Explorer and Safari.

>>  Go to Admin=>System=>Configuration=>Manage Currency=>Symbols. Replace the symbol.

>>  Here is a useful extension that will help you to replace rupee to new symbol. You can configure this one.


Tuesday, January 22, 2013

How to resize product/custom image in magento

>> Resize product image with product object.

          <img src="<?php echo Mage::helper('catalog/image')->init($_product, 'image')->resize(70,155);?>"/>

>> Resize a custom Image.

        // Image name
        $image = "";

        // actual image path
        $imageUrl = Mage::getBaseDir('media'). DS .'justonestepsolution'. DS .$image;
        // Give resized image path to be saved
        // here, the resized image will save in media/justonestepsolution/resized folder
        $imageResized = Mage::getBaseDir('media'). DS .'justonestepsolution'. DS .'resized'. DS .$image;
        // image will resize only if the image file exists and the resized image file doesn't exist

        if (!file_exists($imageResized) && file_exists($imageUrl))
            $imageObj = new Varien_Image($imageUrl);
            $imageObj->resize(300, null);

enjoy :-)

Tuesday, January 15, 2013

Get current logged customer details in magento

>>  $CusSession=mage::getSingleton('customer/session');
    //Checking is logged in customer
        $customer    = $CusSession->getCustomer();     // Customer object
        $name        = $customer->getName();

Wednesday, January 9, 2013

Simple jQuery/html tab

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>jQuery Simple Tab</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
jQuery(document).ready(function() {
     jQuery("ul.tabs li:first").addClass("active").show();
     //On Click Event
     jQuery("ul.tabs li").click(function() {
            jQuery("ul.tabs li").removeClass("active");
            var activeTab = jQuery(this).find("a").attr("href");
            return false;
            return false;

<style type="text/css">
.details-tab-container{width: 800px; height:auto; position:absolute;}
.details-tab{ width:800px; float:left;}
.details-tab ul.tabs{ list-style-type:none;}
.details-tab li{background:#999; border:1px solid; float:left; padding:3px; margin:1px; border-radius: 6px;}
.details-tab li.active{background:#000;}
.details-tab li.active a{color:#FFF; font-size:14px; }
.details-tab li a{ text-decoration:none; font-family:Verdana, Geneva, sans-serif; font-weight:bold; font-size:11px; color:#000;}
.tab-container{ width:800px; float:left; border:2px solid;}

<div class="details-tab-container">
  <div class="details-tab">
    <ul class="tabs">
      <li><a href="#description"><span>Product Description</span></a></li>
      <li><a href="#attribute"><span>Product Attributes</span></a></li>
      <li><a href="#review"><span>Product Reviews</span></a></li>
  <div class="tab-container">
    <div class="tab_content" id="description">Description Lorem ipsum dolor sit amet, tation intellegebat cum ea, at vidit splendide has, te sit ridens salutatus abhorreant. Eum te augue cetero. Clita interpretaris eos cu. Per no senserit suscipiantur. Altera molestie eos ad, pro no fierent periculis. Ponderum convenire sit no.</div>
    <div class="tab_content" id="attribute">Attributes Lorem ipsum dolor sit amet, tation intellegebat cum ea, at vidit splendide has, te sit ridens salutatus abhorreant. Eum te augue cetero. Clita interpretaris eos cu. Per no senserit suscipiantur. Altera molestie eos ad, pro no fierent periculis. Ponderum convenire sit no.</div>
    <div class="tab_content" id="review">Review Lorem ipsum dolor sit amet, tation intellegebat cum ea, at vidit splendide has, te sit ridens salutatus abhorreant. Eum te augue cetero. Clita interpretaris eos cu. Per no senserit suscipiantur. Altera molestie eos ad, pro no fierent periculis. Ponderum convenire sit no.</div>

see the demo here..  :-)

Add social share button with custom image in your web page

>> Add facebook share...
            <a href="javascript:;" onclick="window.open('http://www.facebook.com/share.php?u=your page url','facebook share','resizable=yes,width=700,height=500,scrollbars=yes,status=yes')"><img alt="facebook" src="yourimage.jpg"></a>

>> Twitter Share...
            <a href="javascript:;" onclick="window.open('https://twitter.com/share','twitter share','resizable=yes,width=700,height=500,scrollbars=yes,status=yes')"><img alt="twitter" src="yourimage.jpg"/></a>

>> Pin It share ....
            <a target="_blank" href="http://pinterest.com/pin/create/button/?url=your page url&media=image url&description=image description" class="pin-it-share" count-layout="horizontal"><img alt="pinit" src="yourimage.jpg"></a>


Thursday, January 3, 2013

Magento Error : "You cannot define a correlation name 'size_idx' more than once"....

>> The error occurs if you use <block type="catalog/layer_view" name="catalog.leftnav" after="currency" template="catalog/layer/view.phtml"/> this block twice in your catalog.xml(in your theme folder).
Make sure there is only one layered block.

I got this error when I copied the leftnav block within content block without removing the leftnav block from the left block.

<reference name="left">
            <block type="catalog/layer_view" name="catalog.leftnav" after="currency" template="catalog/layer/view.phtml"/>
<reference name="content">
            <block type="catalog/category_view" name="category.products" template="catalog/category/view.phtml">
                <block type="catalog/layer_view" name="content.leftnav" as="cat_left_nav" template="catalog/layer/view.phtml"/>