Friday, September 28, 2012

Block/Static Block in magento

>> Following is the code by which you can get a Static Block content :

     <?php echo $this->getLayout()->createBlock("cms/block")->setBlockId("identifier")->toHtml() ?>

                  $block = Mage::getModel('cms/block')->load('identifier');
                   echo $block->getTitle();
                   echo $block->getContent();

>> You can also get it from CMS page: Admin=>CMS=>Pages=>Content

     {{block type="cms/block" block_id="my_block" template="cms/content.phtml"}}


>> Create a block programmatically :

       <?php echo $this->getLayout()->createBlock('myModule/block')->setTemplate('folder/custom.phtml')->toHtml();?>

       Note:* If you want to access a method of an existing block. You can do it like:
       $blockObject = $this->getLayout()->createBlock('existingblock/name');
       Now call any method of that block using the $blockObject->yourMethod()

>> Set new template to an existing Block :

     <?php echo $this->getLayout()->createBlock('newsletter/subscribe')->setTemplate('newsletter/subscribe.phtml')->toHtml();?>

>> You can also Pass a variable through block :

      1. Through Admin CMS page. 
      {{block type="core/template" category_id="10" template="page/custom.phtml"}}

      2. In the XML file.
      <block type="core/template" name="" template="catalog/category/visitourstore/subcatlist.phtml" >
               <action method="setData"><name>category_id</name><value>10</value></action>

     3. In The phtml page :
     <?php echo $this->getLayout()->createBlock('core/template')->setData('category_id',10)->setTemplate('page/custom.phtml')->toHtml();?>

   Now you can easily get the value as: <?php echo $this->getCategoryId();  ?>

Tuesday, September 25, 2012

Catalog product collection sort by attribute( select type ) value position

>> By default if you set an attribute(select type) in sort by dropdown. It'll sort by the attribute option's name.
          e.g. Color => 'Black', 'Red', 'White'
     but you want show the product of this attribute like : Color => 'White', 'Black', 'Red'
     Then set the option position here :


      Now open this page : app/code/core/Mage/Eav/Model/Entity/Attribute/Source/Table.php

      Find this function addValueSortToCollection at line 112.

      In this function you'll find the code:

                ->order("{$this->getAttribute()->getAttributeCode()} {$dir}");

      You've to change this code for your "Color" attribute    
      Replace the above code with the following :

      if($this->getAttribute()->getAttributeCode() != 'color'){                // Attribute Code here
                ->order("{$this->getAttribute()->getAttributeCode()} {$dir}");

             $table = Mage::getSingleton('core/resource')->getTableName('eav_attribute_option');
                            ->joinLeft(array('so' => $table), 'IF('.$valueTable2.'.value_id > 0, '.$valueTable2.'.value, '.$valueTable1.'.value) = so.option_id')
                            ->order(array('so.sort_order ASC'));


Now, you'll see the product first which selected 'White' and so on..

Note :  If no color option selected for some product that show at first. So, you've set the color for all products. OR you can change the order   ->order(array('so.sort_order ASC')); To ->order(array('so.sort_order DESC')); and set the position reverse. greater value first.

Wednesday, September 12, 2012

addAttributeToFilter condition in Magento

>> In Magento Collection we frequently use addAttributeToFilter() to append condition in the filter. Here's a simple example :
            $_products = Mage::getModel('catalog/product')->getCollection()
                            ->addAttributeToFilter('status', '1');  
     // This piece of code is used to fetch products of status enabled in Magento
  The same thing if we write in custom sql, it looks like :
            SELECT * FROM `catalog_product_entity` WHERE `status` = '1';
     // I've simplified it in above but Mageto doesn't create sql like this. You can see what magento exactly create by this :
             echo $_products->getSelect();
  We can add all conditions i.e LIKE, IN, NOT IN, IN etc.

         *    To use DATE between condition :

                 $_products->addAttributeToFilter('created_at', array(
                                                                         'from' => '2013-11-01',
                                                                         'to' => '2013-12-02',
                $_products->addAttributeToFilter('created_at', array(
                                                                         'from' => '01 November 2013',
                                                                         'to' => '02 December 2013',
                                                                         'date' => true,

         *    To use EQUAL condition :
                $_products->addAttributeToFilter('status', array('eq' => 1));
        *    To use NOT EQUAL condition :
                $_products->addAttributeToFilter('status', array('neq' => 1));
        *    To use LIKE condition :
                $_products->addAttributeToFilter('name', array('like' => 'polo%'));
        *    To use NOT LIKE condition :
                $_products->addAttributeToFilter('name', array('nlike' => 'polo%'));
        *    To use IN condition :
                $_products->addAttributeToFilter('id', array('in' => array(25,52,41,28)));
        *    To use NOT IN condition :
                $_products->addAttributeToFilter('id', array('nin' => array(25,52,41,28)));
        *    To use IS NULL condition :
                $_products->addAttributeToFilter('description', array('null' => true));
        *    To use NOT NULL condition :
                $_products->addAttributeToFilter('description', array('notnull' => true));
        *    To use GREATER THAN condition :
                $_products->addAttributeToFilter('id', array('gt' => 10));
        *    To use LESS THAN condition :
                $_products->addAttributeToFilter('id', array('lt' => 10));
        *    To use GREATER THAN EQUAL condition :
                $_products->addAttributeToFilter('id', array('gteq' => 10));
        *    To use LESS THAN EQUAL condition :
                $_products->addAttributeToFilter('id', array('lteq' => 10));

        *    To use AND/OR condition :
                $_products->addAttributeToFilter('name', array('eq' => 'xyz'));
                $_products->addAttributeToFilter('name', array('eq' => 'abc'));
                Above code will use with AND condition
                      array('attribute'=>'name', 'eq'=>'xyz'),
                      array('attribute'=>'name', 'eq'=>'abc')
                Above code will use with OR condition




Increase Admin session timeout in magento

>> To increase the session time in admin Go to

                    System => Configuration => Admin => Security => set Session Lifetime (seconds) : value as you want. ( like : 14000).

     Now  go to System => Configuration =>Web => Session Cookie Management => set Cookie Lifetime

  This would be effect after next login.

Thursday, September 6, 2012

Get all categories with tree model in magento

>> This is simple example to get nested category list. You can easily create a left navigation and a drop-down menu with the Retrieved HTML. Follow the code : 

   $rootCatId = Mage::app()->getStore()->getRootCategoryId();
   $catlistHtml = getTreeCategories($rootCatId, false);
   echo $catlistHtml;

function getTreeCategories($parentId, $isChild){
    $allCats = Mage::getModel('catalog/category')->getCollection()
                ->addAttributeToFilter('parent_id',array('eq' => $parentId))
                ->addAttributeToSort('position', 'asc');
    $class = ($isChild) ? "sub-cat-list" : "cat-list";
    $html .= '<ul class="'.$class.'">';
    foreach($allCats as $category)
        $html .= '<li><span>'.$category->getName()."</span>";
        $subcats = $category->getChildren();
        if($subcats != ''){
            $html .= getTreeCategories($category->getId(), true);
        $html .= '</li>';
    $html .= '</ul>';
    return $html;


                                          ***********         Good Luck        **********

Wednesday, September 5, 2012

Create scroll top using jQuery

>> Using this code you can scroll to top. You must scroll down to see the effect.

<html xmlns="">
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>Untitled Document</title>
        <script src=""></script>
        <script type="text/javascript">
                jQuery('html, body').animate({scrollTop: '0px'}, 2000);

        <button id="top">Go Top</button>

Bestseller Products in Magento

>>  You can easily get the bestseller products using this code :

$storeId = Mage::app()->getStore()->getStoreId();
$sales_order = Mage::getSingleton('core/resource')->getTableName('sales_flat_order');
$sales_order_item = Mage::getSingleton('core/resource')->getTableName('sales_flat_order_item');

$_productCollection = Mage::getModel('sales/order_item')->getCollection();

$_productCollection = $_productCollection->addAttributeToSelect('order_id')
                ->addAttributeToFilter('main_table.store_id', $storeId)
                ->addAttributeToFilter('main_table.parent_item_id', array('null' => true));
                   ->join(array('so' => $sales_order), 'main_table.order_id = so.entity_id',  array('so.*'))
                   ->where("so.status <> 'canceled'")
                   ->columns('SUM(main_table.qty_ordered) AS total_qty')
                   ->order(array('total_qty desc'))

foreach($_productCollection as $order)
    $_product = Mage::getModel('catalog/product')->load($order->getProductId());
    ............................................................// show product info here

                         ***********         Good Luck        **********