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()
                            ->addAttributeToSelect('*')
                            ->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
               ===================================
                $_products->addAttributeToFilter(
                  array(
                      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
14000.

  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 : 

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

function getTreeCategories($parentId, $isChild){
    $allCats = Mage::getModel('catalog/category')->getCollection()
                ->addAttributeToSelect('*')
                ->addAttributeToFilter('is_active','1')
                ->addAttributeToFilter('include_in_menu','1')
                ->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="http://www.w3.org/1999/xhtml">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>Untitled Document</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('#top').click(function(){
                jQuery('html, body').animate({scrollTop: '0px'}, 2000);
            });
        });
        </script>
    </head>

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


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')
                ->addAttributeToSelect('product_id')
                ->addAttributeToFilter('main_table.store_id', $storeId)
                ->addAttributeToFilter('main_table.parent_item_id', array('null' => true));
               
$_productCollection->getSelect()
                   ->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'))
                   ->group(array('main_table.product_id'));

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




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




Add attribute option programmatically in magento

 You can easily create attribute options from outside magento using following code :

<?php
require_once 'app/Mage.php';
umask(0);
Mage::app();

function addAttributeOption($attribute_code, $attribute_value) {
    $attribute_model = Mage::getModel('eav/entity_attribute');
    $attribute_options_model= Mage::getModel('eav/entity_attribute_source_table') ;
   
    $attribute_id = $attribute_model->getIdByCode('catalog_product', $attribute_code);
    $attribute = $attribute_model->load($attribute_id);
   
    $attribute_table = $attribute_options_model->setAttribute($attribute);
    $options = $attribute_options_model->getAllOptions(false);

   foreach($options as $option) {
        // checking if already exists
        if ($option['label'] == $attribute_value) {
$optionId = $option['value'];
                return $optionId;
        }
    }

    $value['option'] = array($attribute_value,$attribute_value);
    $result = array('value' => $value);
    $attribute->setData('option',$result);
    $attribute->save();
}

addAttributeOption('color','white');

?>

Note : In this example I've added an option "white" to an attribute "color" of select type.

Magento get Attribute Options


>> Get all Options of an Attribute  : 

    $attribute = Mage::getModel('eav/config')->getAttribute('catalog_product', 'attribute_code');        // attribute code here
    $ingredientArr = array();
    foreach ( $attribute->getSource()->getAllOptions(true, true) as $option)
    {
        $ingredientArr[] = array(
            'value' => $option['value'],
            'label' => $option['label']
        );
    }

Note : $option['value'] is the id and $option['label'] is the option name.