Showing posts with label Magento. Show all posts
Showing posts with label Magento. Show all posts

Monday, October 19, 2015

Magento: Product Bulk Images Deletion

<?php
require_once('../app/Mage.php');
umask(0);
Mage::app('admin');
ini_set('display_errors', 1);
echo 'Delete Imgaes script runing at '.date("Y-m-d h:i:sa").' <br/>';
try{
    $csv = new Varien_File_Csv();
    $csvfilepath = '../../../../tmp/deleteimages.csv';
   
    $cssfile = fopen($csvfilepath,"r");  
    $data = $csv->getData($csvfilepath);
    //Mage::log('CSV file exsist', null, 'bulkimagesimport.log');
    echo 'CSV file exsist <br/>';
    $rows = count($data);
    for ($j = 1; $j<= $rows; $j++) {
        $productSKU = $data[$j][0];
        if(!empty($productSKU)){
            $product = Mage::getModel('catalog/product')->loadByAttribute('sku',$productSKU);
            if (!$product){
                //Mage::log($productSKU.' SKU doesn`t exsist', null, 'bulkimagesimport.log');
                echo $productSKU.' SKU doesn`t exsist <br/>';
            }else{
                //deleting
                Mage::app()->getStore()->setId(Mage_Core_Model_App::ADMIN_STORE_ID);              
                $mediaApi = Mage::getModel("catalog/product_attribute_media_api");
                $product = Mage::getModel('catalog/product')->load($product->getId());
                $items = $mediaApi->items($product->getId());
                $attributes = $product->getTypeInstance()->getSetAttributes();
                $gallery = $attributes['media_gallery'];
                foreach($items as $item){
                    if ($gallery->getBackend()->getImage($product, $item['file'])) {
                        $gallery->getBackend()->removeImage($product, $item['file']);
                    }
                }
                $product->save();
                echo 'Images deleted for sku '.$productSKU.'<br/>';
            }
        }
    }
    fclose($cssfile);
    echo 'Deletion Successfully at '.date("Y-m-d h:i:sa").' <br/>';
}  catch (Exception $e){
    //Mage::log($e->getMessage(), null, 'bulkimagesimport.log');
    echo $e->getMessage();
}  
       

Magento: Import Product Bulk Images

<?php
require_once('../app/Mage.php');
umask(0);
Mage::app('admin');
echo 'Bulk Import Imgaes script runing at '.date("Y-m-d h:i:sa").' <br/>';
try{
    $csv = new Varien_File_Csv();
   
    $csvfilepath = '../../../../tmp/importimage.csv';    
    $imagepath = '../../../../tmp/import/';
    $cssfile = fopen($csvfilepath,"r");  
    $data = $csv->getData($csvfilepath);
    //Mage::log('CSV file exsist', null, 'bulkimagesimport.log');
    echo 'CSV file exsist <br/>';
    $rows = count($data);
   
   
   
    for ($j = 1; $j<= $rows; $j++) {
        $productSKU = $data[$j][0];
        if(!empty($productSKU)){
            $product = Mage::getModel('catalog/product')->loadByAttribute('sku',$productSKU);
            if (!$product){
                //Mage::log($productSKU.' SKU doesn`t exsist', null, 'bulkimagesimport.log');
                echo $productSKU.' SKU doesn`t exsist <br/>';
            }else{
            //Mage::log($productSKU.' SKU product loaded', null, 'bulkimagesimport.log');
            echo $productSKU.' SKU product loaded <br/>';
            $imagesArray = explode('|', $data[$j][1]);          
            $count = 0;
            $mediaAttribute = array (
                'image',
                'small_image',
                'thumbnail',
                'reference_image',
                'faceimage'
            );
            foreach ($imagesArray as $image){
                $imagefile = $imagepath.trim($image);
                if (file_exists($imagefile)) {                          
                    if ($count == 0){
                        $product->addImageToMediaGallery( $imagefile , $mediaAttribute, false, false );
                    }else{
                        $product->addImageToMediaGallery( $imagefile , null, false, false );
                    }
                    $product->setStoreId(0);
                    //Mage::log($imagefile.' Image uploaded', null, 'bulkimagesimport.log');
                    echo $image.' Image uploaded <br/>';
                } else {
                    //Mage::log($imagefile.' Image not found', null, 'bulkimagesimport.log');
                    echo $image.' Image not found <br/>';
                }
                $count++;
            }

            $product->save();
            //Mage::log($productSKU.' SKU uploaded successfully', null, 'bulkimagesimport.log');
            echo $productSKU.' SKU uploaded successfully <br/>';
        }
        }
    }
    fclose($cssfile);
    echo 'Uploaded Successfully at '.date("Y-m-d h:i:sa").' <br/>';
}  catch (Exception $e){
    //Mage::log($e->getMessage(), null, 'bulkimagesimport.log');
    echo $e->getMessage();
}  
       

Wednesday, July 30, 2014

Magento : Difference between “Flush Magento Cache” and “Flush Cache Storage” in magento cache management

Flush Magento Cache

Removes all items in the default Magento cache (var/cache) and the var/full_page cache that have a Magento tag

Flush Cache Storage

Removes all items in the cache. This is the equivalent of deleting the entire contents of the cache folder on the server.If your system uses an alternate cache location, any cached files used by other applications will be removed.

Sunday, June 15, 2014

Add wysiwyg editor in Magento Custom Module

Considering custom module Bd_Demo

Add following function in Bd_Demo_Block_Adminhtml_Demo_Edit

protected function _prepareLayout() {
    parent::_prepareLayout();
    if (Mage::getSingleton('cms/wysiwyg_config')->isEnabled()) {
        $this->getLayout()->getBlock('head')->setCanLoadTinyMce(true);
    }
}

Then use as in grid from  Bd_Demo_Block_Adminhtml_Demo_Edit_Tab_Form
$fieldset->addField("wood_description", "editor", array(
"label" => Mage::helper("woodflooring")->__("Description"),
"class" => "required-entry",
"required" => true,
"name" => "wood_description",
'config'    => Mage::getSingleton('cms/wysiwyg_config')->getConfig(),
'wysiwyg'   => true,
));

Tuesday, May 6, 2014

Magento : SQL Injection in Magento

SQL injection is a technique where malicious users can inject SQL commands into an SQL statement, via web page input.

Binding is the way to go for direct queries in Magento.
As
$write = Mage::getSingleton("core/resource")->getConnection("core_write");
$query = "insert into table_name(name, email, company, description) values (:name, :email, :company, :desc)";
$binds = array(
    'name'      => "name' or 1=1",
    'email'     => "email",
    'company'   => "company",
    'desc'      => "desc",
);
$write->query($query, $binds);

Wednesday, March 19, 2014

Magento : Sort By Newest Product In Category Page

Create a custom module. Suppose, Bd_Sortbynew

Write following code in config.xml
<?xml version="1.0"?>
<config>
<modules>
<Bd_Sortbynew>
<version>0.1.0</version>
</Bd_Sortbynew>
</modules>
<global>
<resources>
<sortbynew_setup>
<setup>
<module>Bd_Sortbynew</module>
                    <class>Mage_Catalog_Model_Resource_Eav_Mysql4_Setup</class>
</setup>
<connection>
<use>core_setup</use>
</connection>
</sortbynew_setup>
</resources>
    </global>
</config>

Then create a sql installer file with following code
$installer = $this;
$installer->startSetup();
$prodEntityTypeId = $installer->getEntityTypeId('catalog_product');
$installer->updateAttribute($prodEntityTypeId, 'created_at', 'frontend_label', 'New');
$installer->updateAttribute($prodEntityTypeId, 'created_at', 'used_for_sort_by', 1);
$installer->endSetup();

For revert you can use following script

require 'app/Mage.php';
Mage::app();

$eavAttribute = new Mage_Eav_Model_Mysql4_Entity_Attribute();
$attribute_id = $eavAttribute->getIdByCode('catalog_product', 'created_at');
if($attribute_id) {
$write = Mage::getSingleton('core/resource')->getConnection('core_write');
$sql  = "update catalog_eav_attribute SET used_for_sort_by = 1 where attribute_id = '$attribute_id' limit 1";
$write->query($sql);
} else {
echo 'Error!';
}

Monday, March 3, 2014

Magento : How do I add a frontend date picker

First create your own module, then follow following step as
1. Add following css & js on that page as
<reference name="head">
        <action method="addItem"><type>js_css</type><name>calendar/calendar-win2k-1.css</name><params/><!--<if/><condition>can_load_calendar_js</condition>--></action>
        <action method="addItem"><type>js</type><name>calendar/calendar.js</name><!--<params/><if/><condition>can_load_calendar_js</condition>--></action>
        <action method="addItem"><type>js</type><name>calendar/calendar-setup.js</name><!--<params/><if/><condition>can_load_calendar_js</condition>--></action>
</reference>

2. Add date filed in your form as
<div class="input-box">                        
                        <input type="text" name="dob" id="dob" title="<?php echo Mage::helper('team')->__('Date Of Birth') ?>" value="" class="input-text required-entry" /> 
                        <img title="Select date" id="dob_trig" src="<?php echo Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_SKIN) . 'adminhtml/default/default/images/grid-cal.gif'; ?>"  class="v-middle"/>
                        <?php echo $this->getLayout()->createBlock('core/html_calendar')->setTemplate('page/js/calendar.phtml'); ?>
                        <script type="text/javascript">
                            Calendar.setup({
                            inputField : 'dob',
                            ifFormat : '%m/%e/%y',
                            button : 'dob_trig',
                            align : 'Bl',
                            singleClick : true
                            });
                        </script> 

<script type="text/javascript">
//<![CDATA[
enUS = {"m":{"wide":["January","February","March","April","May","June","July","August","September","October","November","December"],"abbr":["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]}}; // en_US locale reference
Calendar._DN = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]; // full day names
Calendar._SDN = ["Sun","Mon","Tue","Wed","Thu","Fri","Sat"]; // short day names
Calendar._FD = 0; // First day of the week. "0" means display Sunday first, "1" means display Monday first, etc.
Calendar._MN = ["January","February","March","April","May","June","July","August","September","October","November","December"]; // full month names
Calendar._SMN = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]; // short month names
Calendar._am = "AM"; // am/pm
Calendar._pm = "PM";

// tooltips
Calendar._TT = {};
Calendar._TT["INFO"] = "About the calendar";

Calendar._TT["ABOUT"] =
"DHTML Date/Time Selector\n" +
"(c) dynarch.com 2002-2005 / Author: Mihai Bazon\n" +
"For latest version visit: http://www.dynarch.com/projects/calendar/\n" +
"Distributed under GNU LGPL. See http://gnu.org/licenses/lgpl.html for details." +
"\n\n" +
"Date selection:\n" +
"- Use the \xab, \xbb buttons to select year\n" +
"- Use the " + String.fromCharCode(0x2039) + ", " + String.fromCharCode(0x203a) + " buttons to select month\n" +
"- Hold mouse button on any of the above buttons for faster selection.";
Calendar._TT["ABOUT_TIME"] = "\n\n" +
"Time selection:\n" +
"- Click on any of the time parts to increase it\n" +
"- or Shift-click to decrease it\n" +
"- or click and drag for faster selection.";

Calendar._TT["PREV_YEAR"] = "Prev. year (hold for menu)";
Calendar._TT["PREV_MONTH"] = "Prev. month (hold for menu)";
Calendar._TT["GO_TODAY"] = "Go Today";
Calendar._TT["NEXT_MONTH"] = "Next month (hold for menu)";
Calendar._TT["NEXT_YEAR"] = "Next year (hold for menu)";
Calendar._TT["SEL_DATE"] = "Select date";
Calendar._TT["DRAG_TO_MOVE"] = "Drag to move";
Calendar._TT["PART_TODAY"] = ' (' + "Today" + ')';

// the following is to inform that "%s" is to be the first day of week
Calendar._TT["DAY_FIRST"] = "Display %s first";

// This may be locale-dependent. It specifies the week-end days, as an array
// of comma-separated numbers. The numbers are from 0 to 6: 0 means Sunday, 1
// means Monday, etc.
Calendar._TT["WEEKEND"] = "0,6";

Calendar._TT["CLOSE"] = "Close";
Calendar._TT["TODAY"] = "Today";
Calendar._TT["TIME_PART"] = "(Shift-)Click or drag to change value";

// date formats
Calendar._TT["DEF_DATE_FORMAT"] = "%b %e, %Y";
Calendar._TT["TT_DATE_FORMAT"] = "%B %e, %Y";

Calendar._TT["WK"] = "Week";
Calendar._TT["TIME"] = "Time:";

CalendarDateObject._LOCAL_TIMZEONE_OFFSET_SECONDS = -28800;
CalendarDateObject._SERVER_TIMZEONE_SECONDS = 1333496531;

//]]>
</script>
                        
</div>


Tuesday, February 18, 2014

Magento : Add pagination to Wishlist


Create a custom module then override a core class 'Mage_Wishlist_Block_Customer_Wishlist'
and add following methods _prepareLayout(), getPagerHtml()
as
<?php
class Bd_Custommodulet_Block_Wishlist_Customer_Wishlist extends Mage_Wishlist_Block_Customer_Wishlist
{
     /**
     * Preparing global layout
     *
     * @return Mage_Wishlist_Block_Customer_Wishlist
     */
    protected function _prepareLayout()
    {
        parent::_prepareLayout();
$pager = $this->getLayout()->createBlock('page/html_pager', 'wishlist.customer.pager');
$pager->setAvailableLimit(array(5=>5,10=>10,20=>20,'all'=>'all'));
$pager->setCollection($this->getWishlist());
$this->setChild('pager', $pager);
$this->getWishlist()->load();
return $this;
    }
     /**
     * Pager HTML
     *
     * @return HTML
     */
    public function getPagerHtml()
    {
return $this->getChildHtml('pager');
    }
}

After that add following code in /app/design/frontend/base/default/template/wishlist/view.phtml
<?php echo $this->getPagerHtml(); ?>

Wednesday, January 22, 2014

Magento : Get and Resize Category Images


Override following file app/code/core/Mage/Catalog/Model/Category.php and define following method

public function getCategoryImage(Mage_Catalog_Model_Category $category, $width = 250, $height = 250, $quality = 100)
{
    // return when no image exists
    if (!$category->getImage()) {
        return false;
    }
    // return when the original image doesn't exist
    $imagePath = Mage::getBaseDir('media') . DS . 'catalog' . DS . 'category'
               . DS . $category->getImage();
    if (!file_exists($imagePath)) {
        return false;
    }
    // resize the image if needed
    $rszImagePath = Mage::getBaseDir('media') . DS . 'catalog' . DS . 'category'
                  . DS . 'cache' . DS . $width . 'x' . $height . DS
                  . $category->getImage();
    if (!file_exists($rszImagePath)) {
        $imageObj = new Varien_Image($imagePath);
$imageObj->constrainOnly ( true );
$imageObj->keepAspectRatio ( true );
$imageObj->keepFrame ( false );
$imageObj->quality ( $quality );
$imageObj->resize($width, $height);
        $imageObj->save($rszImagePath);
    }
    // return the image URL
    return Mage::getBaseUrl('media') . '/catalog/category/cache/' . $width . 'x'
         . $height . '/' . $category->getImage();
}

Tuesday, January 21, 2014

Magento : Get thumbnail in navigation


First create your custom module the follow as
1. Override following file app/code/core/Mage/Catalog/Block/Navigation.php
and a function
public function getThumbnailUrl($category)
{
  return Mage::getModel('catalog/category')->load($category->getId())->getThumbnailUrl();
}

2. Then override following file app/code/core/Mage/Catalog/Model/Category.php
and add a function
public function getThumbnailUrl()
{
  $url = false;
  if ($image = $this->getThumbnail()) {
      $url = Mage::getBaseUrl('media').'catalog/category/'.$image;
  }
  return $url;
}

Magento: Improved one page checkout design using CSS


/*  CSS */
.block-progress .block-title { background:none; margin:0 0 34px; padding:0; }
.checkout-onepage-index .col-main { padding:0; border:0; }
.checkout-onepage-index .page-title { padding-right:40px; width:auto; }
.checkout-onepage-index .page-title h1 { background:none; padding:0; }

.opc { position:relative; overflow:hidden; height:970px; padding-top:20px; text-align:center; border:1px solid #BBAFA0; background:#F9F3E3; }
.opc .buttons-set { margin:15px 0 0; opacity:1!important; }
.opc .buttons-set p.required { margin:0; padding:0 0 10px; }
.opc .buttons-set .back-link { display:none; }
.opc .buttons-set .please-wait { position:absolute; z-index:99; top:30%; left:50%; margin:-80px 0 0 -146px; border:5px solid #f3b66f; font-size:12px; background:#fff; padding:30px; white-space:nowrap; border:1px solid #c0c0c0; -moz-border-radius:6px; -webkit-border-radius:6px; border-radius:6px; -moz-box-shadow:1px 1px 2px rgba(0,0,0,0.2); -webkit-box-shadow:0 0 50px rgba(0,0,0,0.2); box-shadow:0 0 50px rgba(0,0,0,0.2); }
.opc .buttons-set a { color:#214D90; }
.opc .ul { list-style:disc outside; padding-left:18px; }
.opc li.section { display:inline; }
.opc .step-title,.opc .allow .step-title { border:1px solid #F9F3E3; height:69px }
.opc .step { padding:30px 20px; position:absolute; border:0; top:110px; left:0; z-index:1; background:#FBFAF6; width:605px; height:900px; border-bottom:1px dotted #ccc; border:none; width:643px; text-align:left; border-top:1px solid #BBAFA0; }
.opc .step-title .number,.opc .allow .step-title .number,.opc .active .step-title .number { float:none; display:block; margin:0 auto; margin-bottom:10px; }
.opc .step-title { position:relative; float:left; text-align:center; padding:15px 11px 0; margin-left:-1px; background:none; }
.opc .step-title a { display:none; }
.opc .step-title .number { background:#ccc; color:#fff; width:30px; height:30px; line-height:30px; -moz-border-radius:20px; -webkit-border-radius:20px; border-radius:20px; margin-bottom:10px; padding:0; border:0; }
.opc .step-title h2 { font-size:12px; color:#bbb; clear:both; }
.opc .allow .step-title { cursor:pointer; background:none; }
.opc .allow .step-title .number { background:#000; color:#fff; }
.opc .allow .step-title h2 { color:#000; }
.opc .active .step-title { color:#ef0606; cursor:default; border:1px solid #BBAFA0; border-bottom:1px solid #FBFAF6; z-index:2; background:#FBFAF6 url(../images/bkg_checkout.gif) 0 0 repeat-x; }
.opc .active .step-title .number { background:#F18200; border-color:#fff; color:#fff; }
.opc .active .step-title h2 { color:#F18200; }
.opc .step-title h2,.opc .allow .step-title h2,.opc .active .step-title h2 { width:100%; text-align:center; }
.opc .step-title { width:16%; }
.opc .form-list .field,.opc .form-list .wide { }
.opc .form-list li fieldset { margin-bottom:40px; }
.opc .form-list label { float:left; width:220px; text-align:right; padding:4px 0 0; }
.opc .form-list label.required em { float:none; position:relative; right:4px; }
.opc .form-list li.fields { margin:0; }
.opc .form-list div.fields { width:100%; overflow:hidden; margin:0 0 8px; }
.opc .form-list .wide,.opc .form-list li.fields .field { width:645px; margin:0 0 8px; }
.opc .form-list li.wide .input-box,.opc .form-list .input-box { clear:none; float:right; margin-right:140px; width:260px; }
.opc .form-list li.wide select { width:390px; }
.opc .form-list li.wide input.input-text { width:254px; }
.opc .form-list .control input { margin:8px 0 0 25px; }
.opc .form-list li.control label { float:left; }
.opc form .form-list li.wide { margin-bottom:8px; }
.opc form .address-select { margin:8px 0 40px; }

.opc:first-of-type .step{-webkit-transition: all 0.5s ease-in-out;-moz-transition: all 0.5s ease-in-out;-o-transition: all 0.5s ease-in-out;-webkit-transition: all 0.5s ease-in-out;transition: all 0.5s ease-in-out;}
.opc:first-of-type .step[style*='display:none;'],
.opc:first-of-type .step[style*='display: none;']{display:block !important;}
.opc:first-of-type .section .step{left: 100%;}
.opc:first-of-type .allow .step{left: -100%;}
.opc:first-of-type .active .step{left:0;}
.opc:first-of-type li:last-child .step-title a{width:50%}
.opc:first-of-type li:first-child .step-title a{width:50%;left:50%}

#opc-login p.required { display:none; }
#opc-login h3 { margin-bottom:18px; }
#opc-login .col-2 { float:left; }
#opc-login .col-2 form fieldset h4 { display:none; }
#opc-login .col-2 { display:block; width:300px; }
#opc-login .col-2 fieldset { width:300px; }
#opc-login .col-2 .input-box { width:188px; margin:0; float:left; }
#opc-login .col-2 .input-text { width:182px; }
#opc-login .col-2 .form-list label { text-align:left; }
#opc-login .col-2 .form-list label { width:110px; }
#opc-login .form-list li.control label { float:none; }
#opc-login .form-list li.control input { margin:0 8px 0 0; }
#opc-login .col-1 { float:right; }
#opc-login .col-1 { width:290px; }
#opc-login .col-1 h4,#opc-login .col-1 .ul { display:none; }
#checkout-step-review.step { width:645px; }

#opc-review .step { padding:30px 20px; border-top:1px solid #BBAFA0; }
#opc-review .product-name { font-weight:bold; color:#0a263c; }
#opc-review .item-options { margin:5px 0 0; }
#opc-review .buttons-set { padding:20px 0; border:0; }
#opc-review .buttons-set p { margin:0; line-height:40px; }
#opc-review .buttons-set .please-wait { height:40px; line-height:40px; }
#opc-shipping_method .buttons-set { border-top:1px solid #E4E4E4; }

.block-progress .block-title { background:none; margin:0 0 34px; padding:0; }
.checkout-onepage-index .col-main { padding:0; border:0; }
.checkout-onepage-index .page-title { padding-right:40px; width:auto; }
.checkout-onepage-index .page-title h1 { background:none; padding:0; }

.opc { position:relative; overflow:hidden; height:970px; padding-top:20px; text-align:center; border:1px solid #BBAFA0; background:#F9F3E3; }
.opc .buttons-set { margin:15px 0 0; opacity:1!important; }
.opc .buttons-set p.required { margin:0; padding:0 0 10px; }
.opc .buttons-set .back-link { display:none; }
.opc .buttons-set .please-wait { position:absolute; z-index:99; top:30%; left:50%; margin:-80px 0 0 -146px; border:5px solid #f3b66f; font-size:12px; background:#fff; padding:30px; white-space:nowrap; border:1px solid #c0c0c0; -moz-border-radius:6px; -webkit-border-radius:6px; border-radius:6px; -moz-box-shadow:1px 1px 2px rgba(0,0,0,0.2); -webkit-box-shadow:0 0 50px rgba(0,0,0,0.2); box-shadow:0 0 50px rgba(0,0,0,0.2); }
.opc .buttons-set a { color:#214D90; }
.opc .ul { list-style:disc outside; padding-left:18px; }
.opc li.section { display:inline; }
.opc .step-title,.opc .allow .step-title { border-color:#FBFAF6; }
.opc .step { padding:30px 20px; position:absolute; border:0; top:100px; left:0; z-index:1; background:#fff; width:605px; height:900px; border-bottom:1px dotted #ccc; border:none; background:none; width:643px; text-align:left; background:#FBFAF6 url(../images/bkg_checkout.gif) 0 0 repeat-x; border-top:1px solid #BBAFA0; }
.opc .step-title .number,.opc .allow .step-title .number,.opc .active .step-title .number { float:none; display:block; margin:0 auto; margin-bottom:10px; }
.opc .step-title a { display:none; }
.opc .step-title .number { background:#fff; color:#ccc; width:30px; height:30px; line-height:30px; -moz-border-radius:20px; -webkit-border-radius:20px; border-radius:20px; margin-bottom:10px; padding:0; border:0; position:relative; z-index:1; }
.opc .step-title h2 { font-size:12px; color:#bbb; clear:both; margin-bottom:10px; }
.opc .allow .step-title .number { background:#000; border-color:#fff; color:#fff; }
.opc .allow .step-title h2 { color:#000; }
.opc .active .step-title .number { background:#F18200; border-color:#fff; color:#fff; }
.opc .active .step-title h2 { color:#F18200; }
.opc .step-title,.opc .allow .step-title,.opc .active .step-title { position:relative; text-align:center; border:none; background:none; padding:0; overflow:hidden!important; height:80px; display:inline-block; vertical-align:top; }
.opc .step-title,.opc .allow .step-title,.opc .active .step-title { *display:block; *float:left; }
.opc .step-title h2,.opc .allow .step-title h2,.opc .active .step-title h2 { width:100%; text-align:center; }
.opc .step-title { width:16%; }
.opc .form-list .field,.opc .form-list .wide { }
.opc .form-list li fieldset { margin-bottom:40px; }
.opc .form-list label { float:left; width:220px; text-align:right; padding:4px 0 0; }
.opc .form-list label.required em { float:none; position:relative; right:4px; }
.opc .form-list li.fields { margin:0; }
.opc .form-list div.fields { width:100%; overflow:hidden; margin:0 0 8px; }
.opc .form-list .wide,.opc .form-list li.fields .field { width:645px; margin:0 0 8px; }
.opc .form-list li.wide .input-box,.opc .form-list .input-box { clear:none; float:right; margin-right:140px; width:260px; }
.opc .form-list li.wide select { width:390px; }
.opc .form-list li.wide input.input-text { width:254px; }
.opc .form-list .control input { margin:8px 0 0 25px; }
.opc .form-list li.control label { float:left; }
.opc form .form-list li.wide { margin-bottom:8px; }
.opc form .address-select { margin:8px 0 40px; }

.opc:first-of-type .step{-webkit-transition: all 0.5s ease-in-out;-moz-transition: all 0.5s ease-in-out;-o-transition: all 0.5s ease-in-out;-webkit-transition: all 0.5s ease-in-out;transition: all 0.5s ease-in-out;}
.opc:first-of-type .step[style*='display:none;'],
.opc:first-of-type .step[style*='display: none;']{display:block !important;}
.opc:first-of-type .section .step{left: 100%;}
.opc:first-of-type .allow .step{left: -100%;}
.opc:first-of-type .active .step{left:0;}
.opc:first-of-type li:last-child .step-title a{width:50%}
.opc:first-of-type li:first-child .step-title a{width:50%;left:50%}
.opc:first-of-type .step-title a { display:block;height:1px;border-bottom:1px dashed #ccc; width:100%; text-indent:-3000px; position: absolute;top:15px;z-index: 0}
.opc:first-of-type .allow .step-title a {}

#opc-login p.required { display:none; }
#opc-login h3 { margin-bottom:18px; }
#opc-login .col-2 { float:left; }
#opc-login .col-2 form fieldset h4 { display:none; }
#opc-login .col-2 { display:block; width:300px; }
#opc-login .col-2 fieldset { width:300px; }
#opc-login .col-2 .input-box { width:188px; margin:0; float:left; }
#opc-login .col-2 .input-text { width:182px; }
#opc-login .col-2 .form-list label { text-align:left; }
#opc-login .col-2 .form-list label { width:110px; }
#opc-login .form-list li.control label { float:none; }
#opc-login .form-list li.control input { margin:0 8px 0 0; }
#opc-login .col-1 { float:right; }
#opc-login .col-1 { width:290px; }
#opc-login .col-1 h4,#opc-login .col-1 .ul { display:none; }

#checkout-step-review.step { width:645px; }
#opc-review .step { padding:30px 20px; border-top:1px solid #BBAFA0; }
#opc-review .product-name { font-weight:bold; color:#0a263c; }
#opc-review .item-options { margin:5px 0 0; }
#opc-review .buttons-set { padding:20px 0; border:0; }
#opc-review .buttons-set p { margin:0; line-height:40px; }
#opc-review .buttons-set .please-wait { height:40px; line-height:40px; }
#opc-shipping_method .buttons-set { border-top:1px solid #E4E4E4; }

Friday, January 10, 2014

Magento: Use ajax filter in magento catalog

There are two things need to do
1.Convert all request into ajax request using following script

function filter(){
    jQuery('.toolbar a').each(function(index){
        jQuery(this).click(function(){
            filterAjax(jQuery( this ).attr('href'));          
            console.log( index + ": " + jQuery( this ).text() ); return false;
        });
     
    });
    jQuery('.toolbar select').each(function(index){
        jQuery(this).removeAttr('onchange');
        jQuery(this).change(function(){
            filterAjax(jQuery( this ).val());
            console.log( index + ": " + jQuery( this ).text() ); return false;
        });
     
    });
    jQuery('.block-layered-nav a').each(function(index){
        jQuery(this).click(function(){        
            filterAjax(jQuery( this ).attr('href'));
            console.log( index + ": " + jQuery( this ).text() ); return false;
        });
     
    });
}
function filterAjax(s_url){
    jQuery('#loader').show();
    jQuery.ajax({
            type: "GET",
            //data : {is_ajax:1},
            url: s_url,
            success: function(data) {
            jQuery('.category-products').remove();
            jQuery('.col-main').append(data.page);                  
            jQuery('.block-layered-nav').remove();
            jQuery('.col-left').prepend(data.block);
            //jQuery('body').append(data.js);
            jQuery('#loader').hide();
            filter();
      }
    });
}
jQuery(document).ready(function(){
    filter();
});

2. Then convert output into JSON using following script

$layout = Mage::getSingleton('core/layout');
if (!$layout)
return;
if (!Mage::app()->getRequest()->isXmlHttpRequest())
return;          
$layout->removeOutputBlock('root');  
Mage::app()->getFrontController()->getResponse()->setHeader('content-type', 'application/json');

$page = $layout->getBlock('product_list');
if (!$page)
return;
$block='';
foreach ($layout->getAllBlocks() as $child){              
if (!in_array($child->getNameInLayout(), array('catalog.leftnav'))){
    continue;
}
$block = $child;
}
if (!$block)
return;      
$container = $layout->createBlock('core/template', 'sparx_container');
//$container->setData('js', $layout->createBlock('core/template', 'ajaxfilter_js')->setTemplate('ajaxfilter/js.phtml')->toHtml());
$container->setData('block', $block->toHtml());
$container->setData('page', $page->toHtml());
$layout->addOutputBlock('sparx_container', 'toJson');

Here we have to use event observer concept.
(controller_action_layout_render_before_catalog_category_view)



Thursday, January 2, 2014

Magento : How to add Indexes in a custom module

Follow these steps:

config.xml:

<index>                              
<indexer>
<cms_indexer>
<model>module/cmsindexer</model>
</cms_indexer>
</indexer>
</index>            

Model:

cmsindexer.php

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
}

Wednesday, December 4, 2013

Magento : Full Page Cache


Full Page Cache (FPC) is:
As in every thing that is generated from a script is written to HTML and served next time, improving performance (by reducing load and not having to generate the page for every visit).


In order to understand Magento Full Page Cache, we need to understand what the run function in Mage_Core_Model_App

public function run($params)
    {
        $options = isset($params['options']) ? $params['options'] : array();
        $this->baseInit($options);
        Mage::register('application_params', $params);

        if ($this->_cache->processRequest()) {
            $this->getResponse()->sendResponse();
        } else {
            $this->_initModules();
            $this->loadAreaPart(Mage_Core_Model_App_Area::AREA_GLOBAL, Mage_Core_Model_App_Area::PART_EVENTS);

            if ($this->_config->isLocalConfigLoaded()) {
                $scopeCode = isset($params['scope_code']) ? $params['scope_code'] : '';
                $scopeType = isset($params['scope_type']) ? $params['scope_type'] : 'store';
                $this->_initCurrentStore($scopeCode, $scopeType);
                $this->_initRequest();
                Mage_Core_Model_Resource_Setup::applyAllDataUpdates();
            }

            $this->getFrontController()->dispatch();
        }
        return $this;
    }

Here $this->_cache->processRequest()
line checks if you have defined a caching node like this under app/etc/test.xml

<config>
<global>
<cache>
<request_processors>
<lt>Bd_Fullpagecache_Model_Processor</lt>
</request_processors>
</cache>
</global>
</config>

The next thing that magento does is to find/initialize the class you have defined and it expects that you have an extractContent function defined in your model.

Friday, November 29, 2013

Magento : Dynamically adding and changing blocks

Store-specific handle:
<STORE_#> (where '#' is the store ID — if you only have one store it is most likely '1')

Category-specific handle:
<CATEGORY_#> (where '#' is the ID number of the current category)

Product-specific handle:
<PRODUCT_#> (where '#' is the ID number of the current product)

Product type-specific handle:
<PRODUCT_TYPE_NAME> (where 'name' is the product type, example: 'simple', 'grouped', 'configurable', etc.)

Customer logged in or out:
<CUSTOMER_LOGGED_STATUS> (where 'status' is either 'in' or 'out')

If CMS page:
<cms_page>

Sunday, September 29, 2013

Bestseller products in Magento

 Using query from database

SELECT `e`.*, `bs`.* FROM `catalog_product_entity` AS `e` INNER JOIN (SELECT `sales_flat_order_item`.`product_id`, SUM(`qty_ordered`) AS `count` FROM `sales_flat_order_item` GROUP BY `product_id`) AS `bs` ON bs.product_id = e.entity_id ORDER BY `bs`.`count` DESC;

And using the collection

$storeId    = Mage::app()->getStore()->getId();
        $products = Mage::getResourceModel('reports/product_collection')
            ->addOrderedQty()
            //->addAttributeToSelect('*')
            ->addAttributeToSelect(array('name', 'price', 'small_image', 'short_description', 'description')) //edit to suit tastes
            ->setStoreId($storeId)
            ->addStoreFilter($storeId)
            ->setOrder('ordered_qty', 'desc'); //best sellers on top      
        Mage::getSingleton('catalog/product_status')->addVisibleFilterToCollection($products);
        Mage::getSingleton('catalog/product_visibility')->addVisibleInCatalogFilterToCollection($products);

        //$products->setPageSize(6)->setCurPage(1);



Tuesday, August 27, 2013

Magento: Store locator in Magento using Google Map API

First you need to create a custom module with single model (one model-one table).
Suppose Bd_Storelocator is a custom module and Storelocator is a model,
Then use following code in any phtml file as
<?php
$requireData = Mage::getModel('storelocator/storelocator')->getStore();
//print_r($requireData->getData());
$markers = "";
$messages = "";
foreach ($requireData as $data) {
    $markers .= '{lat:' . $data["latitude"] . ',lng:' . $data["longitude"] . ',name:' . '"' . $data["storename"] . '"},';
    $messages .= "'" . addslashes($data["storename"]) . "<br/ >" . addslashes($data["address"]) . "<br />" . $data["telephone"] . "', ";    }
$markers1 = rtrim($markers, ",");
$messages1 = rtrim($messages, ", ");
?>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
    var map;
    google.maps.event.addDomListener(window, "load", initialize);
    function initialize() {
        var map = new google.maps.Map(document.getElementById("map_canvas"), {
            mapTypeId: google.maps.MapTypeId.ROADMAP,
            disableAutoPan: false,
            streetViewControl: false
        });
        var markers = [<?php echo $markers1; ?>];
        var widt = document.body.offsetWidth;
        document.getElementById("map_canvas").width = widt+"px";
        for (index in markers) {
            if(Number(index) != index) break;
            addMarker(markers[index],map,index);
        }
        var bounds = new google.maps.LatLngBounds();
        for (index in markers) {
            if(Number(index) != index) break;
            var data = markers[index];
            bounds.extend(new google.maps.LatLng(data.lat, data.lng));
        }
        // Don't zoom in too far on only one marker
        if (bounds.getNorthEast().equals(bounds.getSouthWest())) {
            var extendPoint1 = new google.maps.LatLng(bounds.getNorthEast().lat() + 0.01, bounds.getNorthEast().lng() + 0.01);
            var extendPoint2 = new google.maps.LatLng(bounds.getNorthEast().lat() - 0.01, bounds.getNorthEast().lng() - 0.01);
            bounds.extend(extendPoint1);
            bounds.extend(extendPoint2);
        }
        map.fitBounds(bounds);
    }
    function addMarker(data,map,index) {
        // Create the marker
        //var image = '<?php //print $base_url . '/' . $themePath . '/images/drupal.png'  ?>';
        var marker = new google.maps.Marker({
            position: new google.maps.LatLng(data.lat, data.lng),
            map: map,
            //icon: image,
            title: data.name
        });
        attachSecretMessage(marker,index,map)

    }
    function attachSecretMessage(marker,number,map) {
        var message = [<?php echo $messages1; ?>];

        var infowindow = new google.maps.InfoWindow({
            content: message[number],
            size: new google.maps.Size(50,50)
        });
        google.maps.event.addListener(marker, 'click', function() {
            infowindow.open(map,marker);
           jQuery("#showinfo").html(message[number]);

        });
    }
</script>
<div class="mapBlock">
    <div id="map_canvas" style="height: 473px;">
    </div>
</div>
<div id="showinfo">

</div>

Friday, August 16, 2013

Magento : How to cache custom data into Magento

Use following code in configuration file as
<global>
    <cache>
        <types>
            <namespace_module module="namespace_module" translate="label description">
                <label>Your modules cache label</label>
                <description>Description of your modules cache</description>
                <tags>YOUR_MODULES_CACHE_TAGS</tags>
            </namespace_module>
        </types>
    </cache>
</global>
Then create a model class file witha variable and a method as
const CACHE_TAG_NAMESPACE_MODULE = 'YOUR_MODULES_CACHE_TAGS';
$cacheGroup = 'namespace_module';
$useCache = Mage::app()->useCache($cacheGroup);
if (true === $useCache) {
    // Cache is active
    $cacheId = "unique_name";
    if ($cacheContent = Mage::app()->loadCache($cacheId)) {
    $html = $cacheContent;
    return $html;
    }else{

    try {
        $cacheContent = $html;
        $tags = array(model::CACHE_TAG_NAMESPACE_MODULE);
        $lifetime = Mage::getStoreConfig('core/cache/lifetime');
        Mage::app()->saveCache($cacheContent, $cacheId, $tags, $lifetime);
        } catch (Exception $e) {
        // Exception = no caching
        Mage::logException($e);
    }
    return $html;
    }
} else {
    // Cache is not active
    return $html;
}

Also we can following code for clean the cache
Mage::app()->removeCache($cacheId);


By default Magento uses its file system to save cache (files located in the directory var/cache/).
Another option is the database, which is slower then the files option mostly because the database is a heavily used resource for Magento instances anyway. Then there are storage schemes that use RAM (which are much faster), e.g. APC (shared memory) or memcached (a networked caching server) or Redis.

The Magento cache is organized by tags, this means you have cache entries which belongs to a cache group.

APC is an opcode cache for PHP. It is a framework for caching and optimizing PHP code. APC also serves as a user cache. APC cache is stored in memory where performance gains over file system cache are huge.
There following step to configure APC in Magento
1. Install php5-apc package (like sudo apt-get install php5-apc)
2. Edit and configure setting in apc.ini
3. Add the following code between the global tags in app/etc/local.xml.
<global>
<cache>
            <backend>apc</backend>
            <prefix>mystore_</prefix>
        </cache>
</global>

There following step to configure Memcache as a Fast Backend in Magento
1. Install Memcache as a PHP extension (apt-get install memcached )
2. And enable it in your php.ini
3. Add the following code between the global tags in app/etc/local.xml.
<cache>
<backend>memcached</backend>
<!-- apc / memcached / empty=file -->
<memcached>
<!-- memcached cache backend related config -->
<servers>
<!-- any number of server nodes can be included -->
<server>
<host><![CDATA[127.0.0.1]]></host>
<port><![CDATA[11211]]></port>
<persistent><![CDATA[1]]></persistent>
</server>
</servers>
<compression><![CDATA[0]]></compression>
<cache_dir><![CDATA[]]></cache_dir>
<hashed_directory_level><![CDATA[]]></hashed_directory_level>
<hashed_directory_umask><![CDATA[]]></hashed_directory_umask>
<file_name_prefix><![CDATA[]]></file_name_prefix>
</memcached>
</cache>

There following step to configure Redis as a Fast Backend in Magento
1. Install redis (2.4+ required)
2. Install phpredis
3. Install the magento extension “Cm_Cache_Backend_Redis”
4. Add the following code between the global tags in app/etc/local.xml.
<cache>                                              
<backend>Zend_Cache_Backend_Redis</backend>                            <slow_backend>database</slow_backend>                                  <slow_backend_store_data>0</slow_backend_store_data>                   <auto_refresh_fast_cache>0</auto_refresh_fast_cache>
<backend_options>                                              
<server><![CDATA[127.0.0.1]]></server>
<port><![CDATA[11211]]></port>                                              
<database>database</database>                                        
<use_redisent>0</use_redisent>  <!-- 0 for phpredis, 1 for redisent -->                                                <automatic_cleaning_factor>0</automatic_cleaning_factor> <!-- optional, 20000 is the default, 0 disables auto clean -->
</backend_options>
</cache>

Monday, July 29, 2013

Magento : Install Magento 1.7.0.2 With Sample Data By SSH

mkdir myproject
cd myproject
wget http://www.magentocommerce.com/downloads/assets/1.7.0.2/magento-1.7.0.2.tar.gz
wget http://www.magentocommerce.com/downloads/assets/1.6.1.0/magento-sample-data-1.6.1.0.tar.gz
tar -zxvf magento-1.7.0.2.tar.gz
tar -zxvf magento-sample-data-1.6.1.0.tar.gz
mv magento-sample-data-1.6.1.0/media/* magento/media/
mv magento-sample-data-1.6.1.0/magento_sample_data_for_1.6.1.0.sql magento/data.sql
mv magento/* magento/.htaccess .
chmod o+w var var/.htaccess app/etc
chmod -R o+w media
mysql -h localhost -u -p myproject_db < data.sql
chmod 755 mage
./mage mage-setup.

Wednesday, July 17, 2013

Magento : Create/Collocate Magento System Configuration

First create a blank module with following files
 etc/modules/Bd_Systemconfigdemo.xml
Bd/Systemconfigdemo/etc/config.xml

Then create a system.xml file in  Bd/Systemconfigdemo/etc/system.xml with following code
<?xml version="1.0"?>
<config>
      <tabs>
        <demo_tab translate="label" module="systemconfigdemo">
            <label>Demo Tab</label>
            <sort_order>0</sort_order>
        </demo_tab>
      </tabs>
      <sections>
        <demo_section  translate="label" module="systemconfigdemo">                   
        <label>Demo Section</label>
        <tab>demo_tab</tab>
        <frontend_type>text</frontend_type>
        <sort_order>0</sort_order>
        <show_in_default>1</show_in_default>
        <show_in_website>1</show_in_website>
        <show_in_store>1</show_in_store>           
                    <groups>
                      <demo_group translate="label">
                      <label>Demo Group</label>
                      <frontend_type>text</frontend_type>
                      <sort_order>0</sort_order>
                      <show_in_default>1</show_in_default>
                      <show_in_website>1</show_in_website>
                      <show_in_store>1</show_in_store>
                       <fields>
                          <demo_field1 translate="label">
                            <label>Demo Field1</label>
                            <frontend_type>text</frontend_type>
                            <sort_order>0</sort_order>
                            <show_in_default>1</show_in_default>
                            <show_in_website>1</show_in_website>
                            <show_in_store>1</show_in_store>
                            <comment>first</comment>
                          </demo_field1>
                          <demo_field2 translate="label">
                            <label>Demo Field2</label>
                            <frontend_type>select</frontend_type>
                            <source_model>adminhtml/system_config_source_yesno</source_model>
                            <sort_order>0</sort_order>
                            <show_in_default>1</show_in_default>
                            <show_in_website>1</show_in_website>
                            <show_in_store>1</show_in_store>
                            <comment>second</comment>
                          </demo_field2>
                       </fields>
                       </demo_group>
                    </groups>
        </demo_section>
      </sections>
</config>


And adminhtml.xml with following code
<?xml version="1.0"?>
    <config>
        <acl>
            <resources>
                <admin>
                    <children>
                        <system>
                            <children>
                                <config>
                                    <children>
                                        <demo_section translate="title" module="systemconfigdemo">
                                            <title>Demo Section Section</title>
                                            <sort_order>0</sort_order>
                                        </demo_section>
                                    </children>
                                </config>
                            </children>
                        </system>
                    </children>
                </admin>
            </resources>
        </acl>
    </config>