Monday 21 October 2013

Fly Add to cart javascript code


<!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">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Image Fly To Basket</title>
<script src="http://code.jquery.com/jquery-latest.js"> </script>
<script type="text/javascript">
$(document).ready(function(){
$("#add_to_basket1").click(function(){
var productY = "56";
var productX = "277.5";
var basketY = "91";
var basketX = "926.5";
var gotoY = "35";
var gotoX="649";
var newImageWidth= "23.66666666666667";
var newImageHeight= "44";
$("#imagepreivew1" + " img")
.clone()
.prependTo("#imagepreivew1")
.css({'position' : 'absolute'})
.animate({opacity: 0.4}, 100 )
.animate({opacity: 0.1, marginLeft: gotoX, marginTop: gotoY, width: newImageWidth, height: newImageHeight}, 1200, function() {
$(this).remove();
});
});
});
</script>
<script type="text/javascript">
$(document).ready(function(){
$("#add_to_basket2").click(function(){
var productY = "56";
var productX = "277.5";
var basketY = "91";
var basketX = "926.5";
var gotoY = "35";
var gotoX="649";
var newImageWidth= "23.66666666666667";
var newImageHeight= "44";
$("#imagepreivew2" + " img")
.clone()
.prependTo("#imagepreivew2")
.css({'position' : 'absolute'})
.animate({opacity: 0.4}, 100 )
.animate({opacity: 0.1, marginLeft: gotoX, marginTop: gotoY, width: newImageWidth, height: newImageHeight}, 1200, function() {
$(this).remove();
});
});
});
</script>
</head>
<body>
<div id="imagepreivew1"><img src="http://platinum.best-auction-software.com/public/uploaded_files/products/thumb150x150/5208e51bf1a9792.jpg" border="0" width="100" height="100" /></div>
<div id="add_to_basket1" style="background-color:#666666; color:#FFFFFF; font-weight:bold; width:90px; height:30px; vertical-align:middle; text-align:center;">Add to cart</div>
<div id="imagepreivew2"><img src="http://platinum.best-auction-software.com/public/uploaded_files/products/thumb150x150/5208e51bf1a9792.jpg" border="0" width="100" height="100" /></div>
<div id="add_to_basket2" style="background-color:#666666; color:#FFFFFF; font-weight:bold; width:90px; height:30px; vertical-align:middle; text-align:center;">Add to cart</div>
</body>
</html>


show attribute label and its value or Id in magento

<table>
<tr><td>label</td>
<td>value</td>
</tr>
<?php
$attribute = Mage::getModel('eav/config')->getAttribute('catalog_product', 'manufacturer');
foreach ($attribute->getSource()->getAllOptions(true, true) as $instance) {
?>
<tr>
<td><?php echo $instance['label']; ?></td>
<td><?php echo $instance['value']; ?></td>
</tr>
<?php
}
?>
</table>

How to show special price percentage||discount percentage in Magento


<?php
$_finalPrice = $this->helper('tax')->getPrice($_product, $_product->getFinalPrice());
$_regularPrice = $this->helper('tax')->getPrice($_product, $_product->getPrice());
if ($_regularPrice != $_finalPrice):
$getpercentage = number_format($_finalPrice / $_regularPrice * 100, 2);
$finalpercentage = 100 - $getpercentage;

echo 'SAVE '.number_format($finalpercentage, 0).'%' ;

endif;
?>

change list to any perticular category


----------for a perticular Category--------------------


<?php
//echo $this->getProductCollection()->getSelectSql();
$catagory_model = Mage::getModel('catalog/category')->load('59'); //where $category_id is the id of the category

$_products = Mage::getResourceModel('catalog/product_collection');

$_products->addCategoryFilter($catagory_model); //category filter

$_products->addAttributeToFilter('status',1); //only enabled product

$_products->addAttributeToSelect(array('name','url','small_image','special_price')); //add product attribute to be fetched

//$collection->getSelect()->order('rand()'); //uncomment to get products in random order     
$_products->addAttributeToSort('special_from_date', 'asc');
$_products->addStoreFilter();

//echo count($_products);
?>
<?php if (!empty($_products)): ?>



------------------For all product or another conditionm----------------------


<?php if (($_products = $this->getProductCollection()) && $_products->getSize()): ?>

Thursday 3 October 2013

To export orders with shipping address in magento

Put this script to your magento root and run as: www.youdomain.com/scriptfilename.php


<?
    //
    // Magento CSV Report Script -  Unprocessed Sales Orders
    //
   
    // DATABASE CONNECTION
   
   
    $hostname_MySQLCon="host of database";
    $database_MySQLCon = "database name";
    $username_MySQLCon = "database username";
    $password_MySQLCon = "database password";

    $MySQLCon = mysql_pconnect($hostname_MySQLCon, $username_MySQLCon, $password_MySQLCon);
    $MySQLDb = mysql_select_db($database_MySQLCon, $MySQLCon);
   
    // FUNCTION AREA
   
    function get_DB_Row($query){
        $result = @mysql_query($query);
        $numresults = @mysql_num_rows($result);
       
        for ($i = 0; $i < $numresults; $i++) 
        {
            $row = @mysql_fetch_array($result);
        }
       
        return $row;
    }
   
    // Using this temporary function until I find correct way to pull country names from the database according to two digit code
    // Put in your own until a database polled solution is uncovered
   
   
   
    // INITILISATION AREA
   
    $sitename = "mysite";                  // update this to customise your filename
    $datestring = date('j-m-y');
    $filename = $sitename."-".$datestring;
    $output = "";
   
    $fieldlist = array("orderid","firstname","lastname","address","city","region","country",
    "postcode","telephone","email","itemcode","itemname","quantity","shipping_instructions");
   
    $checklist = array("country", "quantity");
   
    // FIELDLIST INSTRUCTIONS 
    // The order of the CSV fields are set here as well as the field titles
    // The field titles must correspond to a number of SQL Variables being set with the AS operator below
    // If you change the default titles be sure to also update the SQL command accordingly
    // Please note that 'country' and 'quantity' values must be processed but should still be put in your prefered sequence
   
    $numfields = sizeof($fieldlist);
   
    // *********************   NOW START BUILDING THE CSV
   
    // Create the column headers
   
    for($k =0; $k < $numfields;  $k++) { 
        $output .= $fieldlist[$k];
        if ($k < ($numfields-1)) $output .= ", ";
    }
    $output .= "\n";
   
   

    $orderquery = "SELECT * FROM sales_order";      // Query to find unprocessed orders
    $orderresult = mysql_query($orderquery);
    $numorders = @mysql_num_rows($orderresult);
   
    for($i =0; $i < $numorders; $i++) {
        $order = @mysql_fetch_array($orderresult);    // Place each order into an array for proccessing
        $orderid = $order['entity_id'];               // Grab the orderid for use in the main SQL command
       
        // The following SQL command will find all the individual items associated with this order
       
        $itemquery =     "SELECT sales_flat_order_item.order_id AS orderid,
                        sales_flat_order_item.product_type,
                        sales_flat_order_item.quote_item_id,
                        sales_flat_order_item.parent_item_id AS parentid,
                        sales_flat_order_item.sku AS itemcode,
                        sales_flat_order_item.name AS itemname,
                        sales_flat_order_item.qty_ordered AS qty_ordered,
                        sales_flat_order_item.qty_shipped AS qty_shipped,
                        sales_flat_quote_address.email AS email,
                        sales_flat_quote_address.prefix AS title,
                        sales_flat_quote_address.firstname AS firstname,
                        sales_flat_quote_address.lastname AS lastname,
                        sales_flat_quote_address.street AS address,
                        sales_flat_quote_address.city AS city,
                        sales_flat_quote_address.region AS region,
                        sales_flat_quote_address.country_id AS country,
                        sales_flat_quote_address.postcode AS postcode,
                        sales_flat_quote_address.telephone AS telephone,
                        sales_flat_quote_address.shipping_description AS shipping_instructions
                        FROM sales_flat_order_item 
                        INNER JOIN sales_flat_quote_item
                        ON sales_flat_order_item.quote_item_id = sales_flat_quote_item.item_id
                        INNER JOIN sales_flat_quote_address
                        ON sales_flat_quote_item.quote_id = sales_flat_quote_address.quote_id
                        WHERE sales_flat_order_item.order_id = $orderid
                        AND sales_flat_quote_address.address_type = 'shipping' 
                        AND sales_flat_order_item.product_type <> 'configurable'
                        AND sales_flat_order_item.qty_shipped < sales_flat_order_item.qty_ordered";
                       
        $itemresult = mysql_query($itemquery);        // Run the query
        $numitems = @mysql_num_rows($itemresult);   // Check the number of items in the order
       
        for($j =0; $j < $numitems; $j++) {
            $item = @mysql_fetch_array($itemresult); // Place the item in an array for processing
           
            // Output the order item values in the same sequence set in the fieldlist to match headers
           
            for($m =0; $m < sizeof($fieldlist); $m++) { 
               
                $fieldvalue = $fieldlist[$m];
               
                if(in_array($fieldvalue, $checklist)) {                    // check if on special processing list
               
                    if($fieldvalue == "country") $output .= getCountryName($item[$fieldvalue]);
                   
                    if($fieldvalue == "quantity") {
                        $parentid = $item['parentid'];
                        if($parentid == 'NULL') {                          // simple product sold on its own (no parent)
                            $qty_ordered = $item["qty_ordered"];
                            $qty_shipped = $item["qty_shipped"];
                        } else {                                         // simple product was part of bundle or configurable group
                                                                        // If so, use the parent quanities to calculate
                            $parentitem = get_DB_row("SELECT * FROM sales_flat_order_item WHERE item_id = $parentid");
                            $qty_ordered = $parentitem["qty_ordered"];
                            $qty_shipped = $parentitem["qty_shipped"];
                        }
                        $output .= ($qty_ordered - $qty_shipped);
                    }
                   
                } else {
                    $output .= $item[$fieldvalue];
                }
               
                if ($m < ($numfields-1)) $output .= ", ";
            }
           
            $output .= "\n";
        }
       
       
    }
   
    // Send the CSV file to the browser for download
   
    header("Content-type: text/x-csv");
    header("Content-Disposition: attachment; filename=$filename.csv");
    echo $output;
    exit;
   
?>

Thursday 12 September 2013

YouTube important Point:

Full URL : http://www.youtube.com/watch?v=6o65X97CpZU

Videi Key : http://youtu.be/6o65X97CpZU


Image URL : http://img.youtube.com/vi/6o65X97CpZU/0.jpg



http://img.youtube.com/vi/<insert-youtube-video-id-here>/1.jpg
http://img.youtube.com/vi/<insert-youtube-video-id-here>/2.jpg
http://img.youtube.com/vi/<insert-youtube-video-id-here>/3.jpg

show custom attribute in checkout process and order email


you have to add the code in these pages:


/pedal/app/design/adminhtml/default/default/template/sales/order/view/items/renderer/default.phtml

/pedal/app/design/frontend/base/default/template/checkout/onepage/review/item.phtml


/pedal/app/design/frontend/base/default/template/checkout/cart/item/default.phtml

/pedal/app/design/frontend/base/default/template/sales/order/items/renderer/default.phtml


 For Items table (for new order emails):
/app/design/frontend/default/default/template/email/order/items/order/default.phtml

For Items table (for shipment emails):
/app/design/frontend/default/default/template/email/order/items/shipment/default.phtml

For Items table (for invoice emails):
/app/design/frontend/base/default/template/email/order/items/invoice/default.phtml

For Items table (for creditmemo emails):
/app/design/frontend/base/default/template/email/order/items/creditmemo/default.phtml



-----------code---------------------------------------

<?php $_product= Mage::getSingleton('catalog/product')->load($_item->getProductId()) ?>
<?php echo $_product->getResource()->getAttribute('info')->getFrontend()->getValue($_product); ?>

Saturday 31 August 2013

Methods for removing jquery conflict in magento or other cms


<script>
$.noConflict();
jQuery(document).ready(function($) {});
</script>

<script type="text/javascript">
  $.noConflict(); //Use no conflict here instead of js file
  // Code that uses other library's $ can follow here.
</script>

<script type="text/javascript" >
    jQuery.noConflict();
</script >

Above are those methods which helps to solve jquery conflicts in different-2 situation.

Or If its all does not work:

Please check the front-end with rename the library file of jquery.
May be its already include with other conflict script.

Tuesday 27 August 2013

How to overwrite magento controller in local pool


For Example you have to overwrite Mage/Contacts/controller/IndexController.php

Step 1: First you have to make a xml in app/etc/modules/
with name CompanyName_NameSpace.xml

<?xml version="1.0"?>
<config>
  <modules>
    <CompanyName_NameSpace>
      <active>true</active>
      <codePool>local</codePool>
      <version>0.1.0</version>
    </CompanyName_NameSpace>
  </modules>
</config>



Step2: You have to create the folders if not exist in
local/CompanyName/NameSpace/etc/
local/CompanyName/NameSpace/controllers/

In etc folder you have to create a config.xml file
<?xml version="1.0" encoding="utf-8"?>
<config>
    <frontend>
        <routers><!--Depending on the controllers area "frontend" or "admin" -->
            <contacts><!-- base module to rewrite -->
                <args>
                    <modules>
                         <CompanyName_NameSpace before="Mage_Contacts">Shweta_Newscontacts</CompanyName_NameSpace>
                    </modules>
                </args>
            </contacts>
        </routers>
    </frontend>
</config>




In controllers folder copy the Mage/Contacts/controller/IndexController.php file and include the lines:

include_once('Mage/Contacts/controllers/IndexController.php');
and
change the class name as:
class CompanyName_NameSpace_IndexController extends Mage_Core_Controller_Front_Action


Now apply changes in the file you wanted.
Now also, Magento take local pool file instead of core pool.

To show a perticular root category's sub categories with thumbnail images in magento


<div class="product">

<?php
$children = Mage::getModel('catalog/category')->getCategories(3);
$j=1;
?>

<ul>

<?php
foreach ($children as $category):
$category=Mage::getModel('catalog/category')->load($category->getId());
?>
<li>
<div class="new_product">
<div class="pro_detail">
<p><?php echo $category->getName() ?> </p>
</div>
<div class="pro_img"> <a href="<?php echo $category->getUrl() ?>"> <img src="<?php echo Mage::getBaseUrl('media').'catalog/category/'.$category->getThumbnail()  ?>" width="54" height="66" /> </a>
</div>



</div>
</li>
<?php if($j%4=='0') {?>
</ul>
<ul>
<?php } $j++;  endforeach;  ?>
</ul>


</ul>
</div>

Monday 19 August 2013

how to find shipping amount| How to display shipping and handing separately


Add This lines to any where in template file.

This is for getting the full array shipping:

<?php $carriers = Mage::getStoreConfig('carriers', Mage::app()->getStore()->getId());
foreach ($carriers as $carrierCode => $carrierConfig) {

print_R($carrierConfig);

}
?>


This is for getting the flat rate shipping and handling:


  <?php $carriers = Mage::getStoreConfig('carriers', Mage::app()->getStore()->getId());
foreach ($carriers as $carrierCode => $carrierConfig) {
if($carrierConfig[model]=='shipping/carrier_flatrate') {
print_R($carrierConfig[price]);
echo "<br/>";
print_R($carrierConfig[handling_fee]);
}
}
?>

Wednesday 7 August 2013

How to Get Current Url/media,skin,js,home url In magento


To get Current Url
<?php
$currentUrl = $this->helper('core/url')->getCurrentUrl();
?>



Get Magento Url including index.php if not rewrited.

e.g. http://www.example.com/index.php/
Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_LINK);


Get Magento Media Url

e.g. http://www.example.com/media/
Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_MEDIA);


Get Magento Skin Url

e.g. http://www.example.com/skin/
Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_SKIN);


Get Magento Store Url

e.g. http://www.example.com/
Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_WEB);



Get Magento Js Url

e.g. http://www.example.com/js/
Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_JS);



Get Home URL
$magento_home_url = Mage::helper('core/url')->getHomeUrl();


Get not secure Skin URL:
$image = $this->getSkinUrl('images/magento-image.jpg');



Get secure Skin URL
$image = $this->getSkinUrl('images/magento-image.jpg', array('_secure'=>true));


Magento Syntaxes to use in CMS Content.


Get SKIN URL
{{skin url='images/magento-image.jpg '}}
Get Media URL
{{media url='/magento-image.jpg'}}
Get Store URL
{{store url='magento-page.html'}}
Get Base URL
{{base url='magento-page.html'}}


Get full Skin Url inside code

e.g. http://www.example.com/skin/frontend/default/default/
Mage::app()->getLayout()->getBlock('head')->getSkinUrl();

How to exclude/Remove state from shipping in magento


Go to /app/code/core/Mage/Directory/Helper/data.php
Overwrite the default function with this

public function getRegionJson()
{
$exclude_regions = array ('AL','NJ','NY','CT','AS','AK','AA'); //this is the code of excluded state

Varien_Profiler::start('TEST: '.__METHOD__);
if (!$this->_regionJson) {
$cacheKey = 'DIRECTORY_REGIONS_JSON_STORE'.Mage::app()->getStore()->getId();
if (Mage::app()->useCache('config')) {
$json = Mage::app()->loadCache($cacheKey);
}
if (empty($json)) {
$countryIds = array();
foreach ($this->getCountryCollection() as $country) {
$countryIds[] = $country->getCountryId();
}
$collection = Mage::getModel('directory/region')->getResourceCollection()
->addCountryFilter($countryIds)
->load();
$regions = array();
foreach ($collection as $region) {

$rg = $region->getCode();

//if ($rg!=’AL’){
if(!in_array($rg, $exclude_regions)) {

if (!$region->getRegionId()) {
continue;
}
$regions[$region->getCountryId()][$region->getRegionId()] = array(
'code' => $region->getCode(),
//’name’ => $region->getName()
'name' => $this->__($region->getName())
);
}

}
$json = Mage::helper('core')->jsonEncode($regions);

if (Mage::app()->useCache('config')) {
Mage::app()->saveCache($json, $cacheKey, array('config'));
}
}
$this->_regionJson = $json;
}

Varien_Profiler::stop('TEST: '.__METHOD__);
return $this->_regionJson;
}

Monday 15 July 2013

forget password email problem in magento

Go to app/design/frontend/default/[your_custom_theme_folder]/layout/customer.xml

Copy this at the last before: </layout>

<customer_account_resetpassword translate="label">
        <label>Reset a Password</label>
        <remove name="right"/>
        <remove name="left"/>

        <reference name="head">
            <action method="setTitle" translate="title" module="customer">
                <title>Reset a Password</title>
            </action>
        </reference>
        <reference name="root">
            <action method="setTemplate">
                <template>page/1column.phtml</template>
            </action>
            <action method="setHeaderTitle" translate="title" module="customer">
                <title>Reset a Password</title>
            </action>
        </reference>
        <reference name="content">
            <block type="customer/account_resetpassword" name="resetPassword" template="customer/form/resetforgottenpassword.phtml"/>
        </reference>
    </customer_account_resetpassword>

Thursday 11 July 2013

Get Google feed in Magento

make a php file in your Magento root folder and this code and run that file.

Then You can find your text fine in var/export/google_base_feed.txt



<?php
    define('SAVE_FEED_LOCATION','export/google_base_feed.txt');//you can set a new folder and file if you want, don't forget to chmod the folder to 777

    // make sure we don't time out
    set_time_limit(0);   

    require_once 'app/Mage.php';
        Mage::app('default');
       
    try{
        $handle = fopen(SAVE_FEED_LOCATION, 'w');

       
        $heading = array('id','title','description','link','image_link','price','brand','product_type');
        $feed_line=implode("\t", $heading)."\r\n";
        fwrite($handle, $feed_line);
       
        //---------------------- GET THE PRODUCTS   
        $products = Mage::getModel('catalog/product')->getCollection();
        $products->addAttributeToFilter('status', 1);//enabled
        $products->addAttributeToFilter('visibility', 4);//catalog, search
        $products->addAttributeToSelect('*');
        $prodIds=$products->getAllIds();
       
        //echo 'Product filter: '.memory_get_usage(false).'<br>';
        //flush();
       
        $product = Mage::getModel('catalog/product');
       
        foreach($prodIds as $productId) {
            //echo '. ';
            //flush();
            //echo 'Loop start: '.memory_get_usage(false).'<br>';
            //flush();
   
            //$product = Mage::getModel('catalog/product');
            $product->load($productId);
           
            $product_data = array();   
            $product_data['sku']=$product->getSku();   
            $product_data['title']=$product->getName();
            $product_data['description']=$product->getDescription();
            $product_data['link']=$product->getProductUrl();
            $product_data['image_link']=Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_MEDIA).'catalog/product'.$product->getImage();
            $product_data['price']=$product->getPrice();
            $product_data['brand']=$product->getResource()->getAttribute('manufacturer')->getFrontend()->getValue($product);   
            $product_data['product_type']='';       
         
            //echo 'Product load: '.memory_get_usage(false).'<br>';
            //flush();       
         
            //get the product categories                   
                    foreach($product->getCategoryIds() as $_categoryId){
            $category = Mage::getModel('catalog/category')->load($_categoryId);
            $product_data['product_type'].=$category->getName().', ';
            }
            $product_data['product_type']=rtrim($product_data['product_type'],', ');       

            //echo 'Category load: '.(memory_get_usage(false)).'<br>';           
           
            //sanitize data   
            foreach($product_data as $k=>$val){
            $bad=array('"',"\r\n","\n","\r","\t");
            $good=array(""," "," "," ","");
            $product_data[$k] = '"'.str_replace($bad,$good,$val).'"';
            }
           

            $feed_line = implode("\t", $product_data)."\r\n";
            fwrite($handle, $feed_line);
            fflush($handle);
           
            //echo 'Loop end: '.memory_get_usage(false).'<br>';
            //flush();
        }

        //---------------------- WRITE THE FEED   
        fclose($handle);
       
    }
    catch(Exception $e){
        die($e->getMessage());
    }
?>

To show root category's subcategories with thumbnail image in Magento


<div class="product_boxx">
<div id="list_x">
<div class="new_pro">
<ul>
<?php

$children = Mage::getModel('catalog/category')->getCategories(2);
$i=1;
foreach ($children as $category):
$category=Mage::getModel('catalog/category')->load($category->getId());
?>


<li>
<div class="new_promain">
<div class="pro_img"> <a href="<?php echo $category->getUrl() ?>"> <img src="<?php echo Mage::getBaseUrl('media').'catalog/category/'.$category->getThumbnail()  ?>" width="100" height="100" /> </a></div>

<div class="pro_detail">
<p><?php echo $category->getName() ?> </p>
</div>


</div>
</li>


<?php if($i%6=='0') {?>
</ul>
<ul>
<?php } $i++; endforeach; ?>
</ul>
</div>
</div>
</div>

How to call Related product in static Block in Magento

{{block type="catalog/product_list_related" name="catalog.product.related" before="-" template="catalog/product/list/related.phtml"}}

Thursday 20 June 2013

To show review form and customer review on product detail page in magento

To call the all customer review:



{{block type="review/product_view_list" name="product.info.product_additional_data" as="product_additional_data" template="review/product/view/list.phtml"}}

To call the Review Form:


{{block type="review/form" name="product.review.form" as="review_form"}}

Thursday 13 June 2013

Add captcha in contacts us page in magento

Replace this file to your /test/app/design/frontend/base/default/template/contacts/form.phtml

 
<script type="text/javascript">
function ram_mk()
{


a=document.getElementById('tot').value;
b=document.getElementById('catcha').value;
if(a!=b)
{
document.getElementById('mk_x').style.display='';
return false;
}
}

function akk()
{
ab=Math.floor((Math.random()*10)+1);
ab1=Math.floor((Math.random()*8)+1);
var tot=ab+ab1;
document.getElementById('captcha_1').innerHTML=ab;
document.getElementById('captcha_2').innerHTML=ab1;
document.getElementById('tot').value=tot;
document.getElementById('ab').value=ab;
document.getElementById('ab1').value=ab1;

}
window.onload = akk;
</script>
<?php
/**
 * Magento
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the Academic Free License (AFL 3.0)
 * that is bundled with this package in the file LICENSE_AFL.txt.
 * It is also available through the world-wide-web at this URL:
 * http://opensource.org/licenses/afl-3.0.php
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@magentocommerce.com so we can send you a copy immediately.
 *
 * DISCLAIMER
 *
 * Do not edit or add to this file if you wish to upgrade Magento to newer
 * versions in the future. If you wish to customize Magento for your
 * needs please refer to http://www.magentocommerce.com for more information.
 *
 * @category    design
 * @package     base_default
 * @copyright   Copyright (c) 2012 Magento Inc. (http://www.magentocommerce.com)
 * @license     http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
 */
?>
<div class="middle_a">
<?php if($_REQUEST['msg']!='') { ?>
<ul class="messages"><li class="success-msg"><ul><li><span><?php echo $_REQUEST['msg']; ?></span></li></ul></li></ul>
<?php } ?>
<div class="contact_page">
    <h3><?php echo Mage::helper('contacts')->__('got questions?') ?></h3>
<?php echo $this->getLayout()->createBlock('cms/block')->setBlockId('contact-us')->toHtml() ?>
<div class="contact_form">
<form action="http://yourdomain.com/email.php" method="post">
<input type="hidden" name="url_x" value="<?php echo $currentUrl = Mage::helper('core/url')->getCurrentUrl() ?>" />

   <table width="100%" border="0" cellspacing="0" cellpadding="10">
<tr>
       
        <td><input name='name' type='text' class="text-df" onblur="if(this.value=='') this.value='Your Name'" onfocus="if(this.value=='Your Name') this.value=''" value="Your Name" required="required"/></td>
    </tr>
     <tr>
       
        <td><input name='email' type='email' class="text-df" onblur="if(this.value=='') this.value='Email Address'" onfocus="if(this.value=='Email Address') this.value=''" value="Email Address" required="required"/></td>
    </tr>
    <tr>
        <td><textarea name="Message" class="box-df1" required="required" onblur="if(this.value=='') this.value='Message'" onfocus="if(this.value=='Message') this.value=''" value="Message" >Message</textarea>
         </td>
    </tr>
     <tr>
       
        <td><input name="catcha" id="catcha" type='text' class="text-df" onblur="if(this.value=='') this.value='Enter Sum'" onfocus="if(this.value=='Enter Sum') this.value=''" value="Enter Sum" /></td>
    </tr>
    <tr style="display:none; color:#CC0000;" id="mk_x">
    <td align="center">Captcha not match</td>
    </tr>
   
    <tr>
       
        <td>
        <table width="100%">
        <tr>
        <td id="captcha-x">
        <span id="captcha_1">8</span> + <span id="captcha_2">5</span> = ?
       
        <input type="hidden" name="tot" id="tot" value="15"  size="2"/>
        <input type="hidden" name="ab" id="ab" value="15"  size="2"/>
        <input type="hidden" name="ab1" id="ab1" value="15"  size="2"/>
        </td>
        <td align="right">
        <input type='submit' name="submit" value="Send" class="send"  onclick="return ram_mk();" />
        </td>
        </tr>
        </table>
       
        </td>
    </tr>
</table>

</div>




<!-- contact_page -->

</div>

<!-- middle_a -->
<script type="text/javascript">
//<![CDATA[
    var contactForm = new VarienForm('contactForm', true);
//]]>
</script>



and add this file with name email.php to your magento root folder:

<?php
$catcha = $_REQUEST['catcha'];
$tot =$_REQUEST['tot'];
$ab = $_REQUEST['ab'];
$ab1 = $_REQUEST['ab1'];

$total=$ab+$ab1;
if($tot=='@100as_pti')
{
print("<script>window.location='".$_REQUEST['url_x']."'</script>");
exit;

}

if($catcha!=$total)
 {
print("<script>window.location='".$_REQUEST['url_x']."'</script>");
exit;

}



if($catcha==$total)
{

$mesg = $_REQUEST['Message'];
if(stristr($mesg, 'http') === FALSE)
{
if(stristr($mesg, 'https') === FALSE)
{

$_session['success']="Your inquiry was submitted and will be responded to as soon as possible. Thank you for contacting us";
$replymsg="Your inquiry was submitted and will be responded to as soon as possible. Thank you for contacting us";
$mail_to="shweta@ptiwebtech.com";
$sub="Contact us ";

$message = "<br>Name :  ".$_REQUEST['name'];
$message .= "<br>E-mail : ".$_REQUEST['email'];
$message .= "<br>Message  :  ".$_REQUEST['Message'];



$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=iso-8859-1" . "\r\n";
$headers .="From: ".$_REQUEST['email'];

mail($mail_to,$sub,$message,$headers);
}

 }

}

 print("<script>window.location='".$_REQUEST['url_x']."?msg=$replymsg'</script>");
 ?>



NOTE: replace $mail_to="shweta@ptiwebtech.com"; to your email id.

Friday 31 May 2013

You tube playlist call in magento/PHP

<?php
//Playlist: PLAD954BCB770DB285, remove PL from name
$playlist_id = "CKNjaTNxP2sJnqHzGXy45d203O73gPPc";
$url = "https://gdata.youtube.com/feeds/api/playlists/".$playlist_id."?v=2&alt=json";
$data = json_decode(file_get_contents($url),true);
$info = $data["feed"];
$video = $info["entry"];
$nVideo = count($video);

echo "Playlist Name: ".$info["title"]['$t'].'<br/>';
echo "Number of Videos (".$nVideo."):<br/>";
for($i=0;$i<$nVideo;$i++){
    echo "Name: ".$video[$i]['title']['$t'].'<br/>';
    echo "Link: ".$video[$i]['link'][0]['href'].'<br/>';
    echo "Image: <img src='".$video[$i]['media$group']['media$thumbnail'][1]['url']."' /><br />";
}
 ?>


after this you have to register your wbsite to this google account:

https://accounts.google.com/ServiceLogin?service=youtubepartnersyn&passive=true&nui=1&continue=http://code.google.com/apis/youtube/dashboard/gwt/index.html&followup=http://code.google.com/apis/youtube/dashboard/gwt/index.html

customize of label "choose an option" of configurable product in magento


Step 1: Change in catalog/product/view/type/options/configurable.phml

 <?php
$_product = $this->getProduct();
$_attributes = Mage::helper('core')->decorateArray($this->getAllowAttributes());
?>
<?php if ($_product->isSaleable() && count($_attributes)):?>
    <dl>
    <?php foreach($_attributes as $_attribute): ?>
        <?php
        $_attributeId = $_attribute->getAttributeId();
        $_attributeInfo = Mage::getModel('eav/entity_attribute')->load($_attributeId);
        $_attributeLabel = str_replace(' ','-',strtolower($_attributeInfo->getFrontendLabel()));
        ?>
            <dd<?php if ($_attribute->decoratedIsLast){?> class="last"<?php }?>>
                <div class="input-box">
                    <select name="super_attribute[<?php echo $_attribute->getAttributeId() ?>]" id="attribute<?php echo $_attribute->getAttributeId() ?>" class="required-entry super-attribute-select kevin-black-<?php echo $_attributeLabel;?>">
                    <option><?php echo 'choose a '.$_attributeInfo->getFrontendLabel() ?></option>
                    </select>
                </div>
            </dd>
        <?php endforeach; ?>
    </dl>
<script type="text/javascript">
    var spConfig = new Product.Config(<?php echo $this->getJsonConfig() ?>);
    //kevin.qazware@gmail.com Change Text follow attribute Label
    function changeFristText(){
        <?php foreach($_attributes as $_attribute): ?>
            <?php
            $_attributeId = $_attribute->getAttributeId();
            $_attributeInfo = Mage::getModel('eav/entity_attribute')->load($_attributeId);
            ?>
            var label = '<?php echo $_attributeInfo->getFrontendLabel();?>';
            $$('select.kevin-black-'+label).each(function(elem){
                var options = elem.childElements();
                options[0].update(label);
            });
        <?php endforeach;?>
    }
</script>
<?php endif;?>

Step 2: js/varien/configurable.js

replace line 171 = element.options[0] = new Option(element.config.label, '');

Step 3: app/design/frontend/default/grayscale/template/catalog/product/view/type/options/configurable.php
change this line:

'label' => 'choose a '.$attribute->getLabel(),

Calling the list page and toolbar in any cms page in magento || call the category product in cms page in magento

It can also show the products of perticular category.

Go to admin->cms->page->design(layout Xml)

Put this code to layout Xml tab:

<reference name="content">
<block type="catalog/product_list" name="home" template="catalog/product/list.phtml">
<action method="setCategoryId"><category_id>137</category_id></action>

<action method="addColumnCountLayoutDepend"><layout>one_column</layout><count>5</count></action>
<block type="catalog/product_list_toolbar" name="product_list_toolbar" template="catalog/product/list/toolbar.phtml">
<block type="page/html_pager" name="product_list_toolbar_pager"/>
 </block>
<action method="setToolbarBlockName"><name>product_list_toolbar</name><count>5</count></action>
</block>
 </reference>

Wednesday 8 May 2013

simple script to delete all canceled product in magento.

Paste it in a file and place it in root and run. It will delete all canceled order from your magento store.



<?php
require_once('app/Mage.php');
Mage::app('admin');
Mage::getSingleton("core/session", array("name" => "adminhtml"));
Mage::register('isSecureArea',true);
 $collection = Mage::getResourceModel('sales/order_collection')
            ->addAttributeToSelect('*')
            ->setPageSize(5000)          
            ->addFieldToFilter('status', 'canceled')->load();

foreach ($collection as $col) {
  Mage::log($col->getIncrementId() . ' order deleted ');
    try {
         $col->delete();
    } catch (Exception $e) {
        throw $e;
    }
}
?>

How to increase page speed in magento:('without merge css and javascript files')

In you htaccess file do chages as:

Uncomment the line
 php_flag zlib.output_compression on
means remove '#' from starting of php_flag zlib.output_compression on.

write these line in your htaccess file

<IfModule mod_expires.c>

# Enable expirations

ExpiresActive On

# Default directive

ExpiresDefault "access plus 1 year"

# My favicon

ExpiresByType image/x-icon "access plus 1 year"

# Images

ExpiresByType image/gif "access plus 1 year"

ExpiresByType image/png "access plus 1 year"

ExpiresByType image/jpg "access plus 1 year"

ExpiresByType image/jpeg "access plus 1 year"

# CSS

ExpiresByType text/css "access 1 year"

# Javascript

ExpiresByType application/javascript "access plus 1 year"

</IfModule>


Uncomment the lines:

SetOutputFilter DEFLATE
AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css text/javascript
BrowserMatch ^Mozilla/4 gzip-only-text/html
BrowserMatch ^Mozilla/4\.0[678] no-gzip
BrowserMatch \bMSIE !no-gzip !gzip-only-text/html
SetEnvIfNoCase Request_URI \.(?:gif|jpe?g|png)$ no-gzip dont-vary
Header append Vary User-Agent env=!dont-vary


means remove '#' from starting of these lines.

How to increase page speed in magento:('without merge css and javascript files')

In you htaccess file do chages as:

Uncomment the line
 php_flag zlib.output_compression on
means remove '#' from starting of php_flag zlib.output_compression on.

write these line in your htaccess file

<IfModule mod_expires.c>

# Enable expirations

ExpiresActive On

# Default directive

ExpiresDefault "access plus 1 year"

# My favicon

ExpiresByType image/x-icon "access plus 1 year"

# Images

ExpiresByType image/gif "access plus 1 year"

ExpiresByType image/png "access plus 1 year"

ExpiresByType image/jpg "access plus 1 year"

ExpiresByType image/jpeg "access plus 1 year"

# CSS

ExpiresByType text/css "access 1 year"

# Javascript

ExpiresByType application/javascript "access plus 1 year"

</IfModule>


Uncomment the lines:

SetOutputFilter DEFLATE
AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css text/javascript
BrowserMatch ^Mozilla/4 gzip-only-text/html
BrowserMatch ^Mozilla/4\.0[678] no-gzip
BrowserMatch \bMSIE !no-gzip !gzip-only-text/html
SetEnvIfNoCase Request_URI \.(?:gif|jpe?g|png)$ no-gzip dont-vary
Header append Vary User-Agent env=!dont-vary


means remove '#' from starting of these lines.

How to increase page speed in magento:('without merge css and javascript files')


Reindexing of Product Flat Data in magento:

You have to truncate all the 'catalog_product_flat_i' table:
where 'i' can be 1,2,3,4,....

In my case there are 3 table so i fire this query to my phpmyadmin:
TRUNCATE `catalog_product_flat_1`;
TRUNCATE `catalog_product_flat_2`;
TRUNCATE `catalog_product_flat_3`;

Delete Orders From Magento and Reset The Order Id

SET FOREIGN_KEY_CHECKS=0;

TRUNCATE `sales_flat_order`;
TRUNCATE `sales_flat_order_address`;
TRUNCATE `sales_flat_order_grid`;
TRUNCATE `sales_flat_order_item`;
TRUNCATE `sales_flat_order_payment`;
TRUNCATE `sales_flat_order_status_history`;

TRUNCATE `sales_flat_creditmemo`;
TRUNCATE `sales_flat_creditmemo_comment`;
TRUNCATE `sales_flat_creditmemo_grid`;
TRUNCATE `sales_flat_creditmemo_item`;

TRUNCATE `sales_flat_invoice`;
TRUNCATE `sales_flat_invoice`;
TRUNCATE `sales_flat_invoice_grid`;
TRUNCATE `sales_flat_invoice_item`;

TRUNCATE `sales_flat_quote`;
TRUNCATE `sales_flat_quote_address`;
TRUNCATE `sales_flat_quote_address_item`;
TRUNCATE `sales_flat_quote_item`;
TRUNCATE `sales_flat_quote_item_option`;
TRUNCATE `sales_flat_order_item`;

TRUNCATE `sales_flat_shipment`;
TRUNCATE `sales_flat_shipment_comment`;
TRUNCATE `sales_flat_shipment_grid`;
TRUNCATE `sales_flat_shipment_item`;
TRUNCATE `sales_flat_shipment_item`;
TRUNCATE `sales_flat_shipment_track`;

TRUNCATE `sendfriend_log`;
TRUNCATE `tag`;
TRUNCATE `tag_relation`;
TRUNCATE `tag_summary`;
TRUNCATE `wishlist`;
TRUNCATE `log_quote`;
TRUNCATE `report_event`;

ALTER TABLE `sales_flat_order` AUTO_INCREMENT=0;
ALTER TABLE `sales_flat_order_address` AUTO_INCREMENT=0;
ALTER TABLE `sales_flat_order_grid` AUTO_INCREMENT=0;
ALTER TABLE `sales_flat_order_item` AUTO_INCREMENT=0;
ALTER TABLE `sales_flat_order_payment` AUTO_INCREMENT=0;
ALTER TABLE `sales_flat_order_status_history` AUTO_INCREMENT=0;

ALTER TABLE `sales_flat_creditmemo` AUTO_INCREMENT=0;
ALTER TABLE `sales_flat_creditmemo_comment` AUTO_INCREMENT=0;
ALTER TABLE `sales_flat_creditmemo_grid` AUTO_INCREMENT=0;
ALTER TABLE `sales_flat_creditmemo_item` AUTO_INCREMENT=0;

ALTER TABLE `sales_flat_invoice` AUTO_INCREMENT=0;
ALTER TABLE `sales_flat_invoice` AUTO_INCREMENT=0;
ALTER TABLE `sales_flat_invoice_grid` AUTO_INCREMENT=0;
ALTER TABLE `sales_flat_invoice_item` AUTO_INCREMENT=0;

ALTER TABLE `sales_flat_quote` AUTO_INCREMENT=0;
ALTER TABLE `sales_flat_quote_address` AUTO_INCREMENT=0;
ALTER TABLE `sales_flat_quote_address_item` AUTO_INCREMENT=0;
ALTER TABLE `sales_flat_quote_item` AUTO_INCREMENT=0;
ALTER TABLE `sales_flat_quote_item_option` AUTO_INCREMENT=0;
ALTER TABLE `sales_flat_order_item` AUTO_INCREMENT=0;

ALTER TABLE `sales_flat_shipment` AUTO_INCREMENT=0;
ALTER TABLE `sales_flat_shipment_comment` AUTO_INCREMENT=0;
ALTER TABLE `sales_flat_shipment_grid` AUTO_INCREMENT=0;
ALTER TABLE `sales_flat_shipment_item` AUTO_INCREMENT=0;
ALTER TABLE `sales_flat_shipment_item` AUTO_INCREMENT=0;
ALTER TABLE `sales_flat_shipment_track` AUTO_INCREMENT=0;

ALTER TABLE `sendfriend_log` AUTO_INCREMENT=0;
ALTER TABLE `tag` AUTO_INCREMENT=0;
ALTER TABLE `tag_relation` AUTO_INCREMENT=0;
ALTER TABLE `tag_summary` AUTO_INCREMENT=0;
ALTER TABLE `wishlist` AUTO_INCREMENT=0;
ALTER TABLE `log_quote` AUTO_INCREMENT=0;
ALTER TABLE `report_event` AUTO_INCREMENT=0;

TRUNCATE `eav_entity_store`;
ALTER TABLE  `eav_entity_store` AUTO_INCREMENT=0;

SET FOREIGN_KEY_CHECKS=1;

remove customer and reset id in magento

Run the Query in phpmyadmin.
Note: Before use Backup your database:

    TRUNCATE TABLE `customer_address_entity`;
    TRUNCATE TABLE `customer_address_entity_datetime`;
    TRUNCATE TABLE `customer_address_entity_decimal`;
    TRUNCATE TABLE `customer_address_entity_int`;
    TRUNCATE TABLE `customer_address_entity_text`;
    TRUNCATE TABLE `customer_address_entity_varchar`;
    TRUNCATE TABLE `customer_entity`;
    TRUNCATE TABLE `customer_entity_datetime`;
    TRUNCATE TABLE `customer_entity_decimal`;
    TRUNCATE TABLE `customer_entity_int`;
    TRUNCATE TABLE `customer_entity_text`;
    TRUNCATE TABLE `customer_entity_varchar`;

remove category and reset id in magento:

Run the Query in phpmyadmin.
Note: Before use Backup your database:

    TRUNCATE TABLE `catalog_category_entity`;
    TRUNCATE TABLE `catalog_category_entity_datetime`;
    TRUNCATE TABLE `catalog_category_entity_decimal`;
    TRUNCATE TABLE `catalog_category_entity_int`;
    TRUNCATE TABLE `catalog_category_entity_text`;
    TRUNCATE TABLE `catalog_category_entity_varchar`;
    TRUNCATE TABLE `catalog_category_product`;
    TRUNCATE TABLE `catalog_category_product_index`;
    
    INSERT  INTO `catalog_category_entity`(`entity_id`,`entity_type_id`,`attribute_set_id`,`parent_id`,`created_at`,`updated_at`,`path`,`POSITION`,`level`,`children_count`) VALUES (1,3,0,0,'0000-00-00 00:00:00','2009-02-20 00:25:34','1',1,0,1),(2,3,3,0,'2009-02-20 00:25:34','2009-02-20 00:25:34','1/2',1,1,0);
    INSERT  INTO `catalog_category_entity_int`(`value_id`,`entity_type_id`,`attribute_id`,`store_id`,`entity_id`,`value`) VALUES (1,3,32,0,2,1),(2,3,32,1,2,1);
    INSERT  INTO `catalog_category_entity_varchar`(`value_id`,`entity_type_id`,`attribute_id`,`store_id`,`entity_id`,`value`) VALUES (1,3,31,0,1,'Root Catalog'),(2,3,33,0,1,'root-catalog'),(3,3,31,0,2,'Default Category'),(4,3,39,0,2,'PRODUCTS'),(5,3,33,0,2,'default-category');
    
    /**** Magento ver. 1.6.x.x ****/
    
    TRUNCATE TABLE `catalog_category_entity`;
    TRUNCATE TABLE `catalog_category_entity_datetime`;
    TRUNCATE TABLE `catalog_category_entity_decimal`;
    TRUNCATE TABLE `catalog_category_entity_int`;
    TRUNCATE TABLE `catalog_category_entity_text`;
    TRUNCATE TABLE `catalog_category_entity_varchar`;
    TRUNCATE TABLE `catalog_category_product`;
    TRUNCATE TABLE `catalog_category_product_index`;
    
    INSERT  INTO `catalog_category_entity`(`entity_id`,`entity_type_id`,`attribute_set_id`,`parent_id`,`created_at`,`updated_at`,`path`,`POSITION`,`level`,`children_count`) VALUES (1,3,0,0,'0000-00-00 00:00:00','0000-00-00 00:00:00','1',1,0,1), (2,3,3,1,'0000-00-00 00:00:00','0000-00-00 00:00:00','1/2','1','1','0');
    INSERT  INTO `catalog_category_entity_int`(`value_id`,`entity_type_id`,`attribute_id`,`store_id`,`entity_id`,`value`) VALUES (1,3,32,0,2,1),(2,3,36,0,2,1),(3,3,61,0,2,1),(4,3,44,0,2,NULL),(5,3,45,0,2,1),(6,3,62,0,2,1),(7,3,63,0,2,1),(8,3,64,0,2,NULL);
    INSERT  INTO `catalog_category_entity_varchar`(`value_id`,`entity_type_id`,`attribute_id`,`store_id`,`entity_id`,`value`) VALUES (1,3,31,0,1,'Root Catalog'),(2,3,35,0,2,'Default Category'),(3,3,37,0,2,'default-category'),(4,3,40,0,2,NULL),(5,3,43,0,2,'PRODUCTS'),(6,3,52,0,2,NULL),(7,3,55,0,2,NULL);
    

Removing products and reset id in magento

Run the Query in phpmyadmin.
Note: Before use Backup your database:

Delete products:

    TRUNCATE TABLE `catalog_product_bundle_option`;
    TRUNCATE TABLE `catalog_product_bundle_option_value`;
    TRUNCATE TABLE `catalog_product_bundle_selection`;
    TRUNCATE TABLE `catalog_product_entity_datetime`;
    TRUNCATE TABLE `catalog_product_entity_decimal`;
    TRUNCATE TABLE `catalog_product_entity_gallery`;
    TRUNCATE TABLE `catalog_product_entity_int`;
    TRUNCATE TABLE `catalog_product_entity_media_gallery`;
    TRUNCATE TABLE `catalog_product_entity_media_gallery_value`;
    TRUNCATE TABLE `catalog_product_entity_text`;
    TRUNCATE TABLE `catalog_product_entity_tier_price`;
    TRUNCATE TABLE `catalog_product_entity_varchar`;
    TRUNCATE TABLE `catalog_product_link`;
    TRUNCATE TABLE `catalog_product_link_attribute`;
    TRUNCATE TABLE `catalog_product_link_attribute_decimal`;
    TRUNCATE TABLE `catalog_product_link_attribute_int`;
    TRUNCATE TABLE `catalog_product_link_attribute_varchar`;
    TRUNCATE TABLE `catalog_product_link_type`;
    TRUNCATE TABLE `catalog_product_option`;
    TRUNCATE TABLE `catalog_product_option_price`;
    TRUNCATE TABLE `catalog_product_option_title`;
    TRUNCATE TABLE `catalog_product_option_type_price`;
    TRUNCATE TABLE `catalog_product_option_type_title`;
    TRUNCATE TABLE `catalog_product_option_type_value`;
    TRUNCATE TABLE `catalog_product_super_attribute`;
    TRUNCATE TABLE `catalog_product_super_attribute_label`;
    TRUNCATE TABLE `catalog_product_super_attribute_pricing`;
    TRUNCATE TABLE `catalog_product_super_link`;
    TRUNCATE TABLE `catalog_product_enabled_index`;
    TRUNCATE TABLE `catalog_product_website`;
    TRUNCATE TABLE `catalog_product_entity`;
    
    TRUNCATE TABLE `cataloginventory_stock`;
    TRUNCATE TABLE `cataloginventory_stock_item`;
    TRUNCATE TABLE `cataloginventory_stock_status`;
    
    INSERT  INTO `catalog_product_link_type`(`link_type_id`,`code`) VALUES (1,'relation'),(2,'bundle'),(3,'super'),(4,'up_sell'),(5,'cross_sell');
    INSERT  INTO `catalog_product_link_attribute`(`product_link_attribute_id`,`link_type_id`,`product_link_attribute_code`,`data_type`) VALUES (1,2,'qty','decimal'),(2,1,'position','int'),(3,4,'position','int'),(4,5,'position','int'),(6,1,'qty','decimal'),(7,3,'position','int'),(8,3,'qty','decimal');
    INSERT  INTO `cataloginventory_stock`(`stock_id`,`stock_name`) VALUES (1,'Default');

Change the label of shipping and handing in magento

Go to this path
app/code/core/Mage/Sales/Model/Quote/Address/Total/
open shipping.php
there is a function fetch()
In this see the $title value content the 'Shipping & Handling' change it to your custom text.

Monday 6 May 2013

Get product Description on order in magento

For backend order:


/test/app/design/adminhtml/default/default/template/sales/order/view/items/renderer/default.phtml



add lines after first td closed:-
<td><?php $custom2=Mage::getModel('catalog/product')->load($_item->getId());
echo $custom2->getDescription();
?>
</td>


/test/app/design/adminhtml/default/default/template/sales/order/view/item.phtml


after the line  <th><?php echo $this->helper('sales')->__('Product') ?></th>


add the line:
<th><?php echo $this->helper('sales')->__('Product Description') ?></th>



For frondend order In my account:
/test/app/design/frontend/base/default/template/sales/order/items/renderer/default.phtml
add this line after first td close

<td><?php $custom2=Mage::getModel('catalog/product')->load($_item->getId());
echo $custom2->getDescription();
?> </td>



/test/app/design/frontend/base/default/template/sales/order/item.phtml

after line this "  <th><?php echo $this->__('Product Name') ?></th>"

add the lines:
<th><?php echo $this->__('Product Discription') ?></th>


For cart page in frountend:

/app/design/frontend/base/default/template/checkout/cart/item/default.phtml

<td><?php $custom2=Mage::getModel('catalog/product')->load($_item->getId());
echo $custom2->getDescription();
?> </td>


/app/design/frontend/base/default/template/checkout/cart.phtml
  <th rowspan="<?php echo $mergedCells; ?>"><span class="nobr"><?php echo $this->__('Product Description') ?></span></th>

show All category with their thumbnail image in magento

first create a page in template/catalog/navigation
category_listing.phtml

Paste the below code:

 <?php
$_main_categories=$this->getStoreCategories();
if($_main_categories->count()):
    foreach ($_main_categories as $_main_category):
     
              ?>
                    <?php
                    $cur_category=Mage::getModel('catalog/category')->load($_main_category->getId());
                    $layer = Mage::getSingleton('catalog/layer');
                    $layer->setCurrentCategory($cur_category);
                   ?>               

                    <div class="catagory-box">
                        <div class="greenBorder">
                            <div class="img-align">
                                <div class="img-valign" align="center">
                                    <a href="<?php echo $this->getCurrentCategory()->getUrl()?>">
    <?php if($_imageUrl=$this->getCurrentCategory()->getThumbnailImageUrl()):?>
       <img src="<?php echo $_imageUrl ?>" alt="<?php echo $this->getCurrentCategory()->getName();?>" width="100" height="100">
                                    <?php else:?>
    <img src="<?php echo $this->getSkinUrl('images/add-01.gif')?>" alt="<?php echo $this->getCurrentCategory()->getName();?>">
                                    <?php endif;?>
                                    </a>
                                </div>
                            </div>
                        </div>
                        <div class="cat-box-text">
                            <span><a href="<?php echo $this->getCurrentCategory()->getUrl()?>"><?php echo $this->getCurrentCategory()->getName();?></a></span><br>
                            <?php echo $this->getCurrentCategory()->getDescription() ?>
                        </div>
                    </div>
<?php
          $_sub_categories=$_main_category->getChildren();
            foreach ($_sub_categories as $_sub_category): ?>
<?php
                    $cur_category1=Mage::getModel('catalog/category')->load($_sub_category->getId());
                    $layer = Mage::getSingleton('catalog/layer');
                    $layer->setCurrentCategory($cur_category1);
?><div class="catagory-box">
                        <div class="greenBorder">
                            <div class="img-align">
                                <div class="img-valign" align="center">
                                    <a href="<?php echo $this->getCurrentCategory()->getUrl()?>">
    <?php if($_imageUrl=$this->getCurrentCategory()->getThumbnailImageUrl()):?>
       <img src="<?php echo $_imageUrl?>" alt="<?php echo $this->getCurrentCategory()->getName();?>" width="100" height="100">
                                    <?php else:?>
    <img src="<?php echo $this->getSkinUrl('images/add-01.gif')?>" alt="<?php echo $this->getCurrentCategory()->getName();?>">
                                    <?php endif;?>
                                    </a>
                                </div>
                            </div>
                        </div>
                        <div class="cat-box-text">
                            <span><a href="<?php echo $this->getCurrentCategory()->getUrl()?>"><?php echo $this->getCurrentCategory()->getName();?></a></span><br>
                            <?php echo $this->getCurrentCategory()->getDescription() ?>
                        </div>
                    </div>
<?php
          $_sub_sub_categories=$_sub_category->getChildren();
            foreach ($_sub_sub_categories as $_sub_sub_category): ?>
<?php
                    $cur_category2=Mage::getModel('catalog/category')->load($_sub_sub_category->getId());
                    $layer = Mage::getSingleton('catalog/layer');
                    $layer->setCurrentCategory($cur_category2);
?><div class="catagory-box">
                        <div class="greenBorder">
                            <div class="img-align">
                                <div class="img-valign" align="center">
                                    <a href="<?php echo $this->getCurrentCategory()->getUrl()?>">
    <?php if($_imageUrl=$this->getCurrentCategory()->getThumbnailImageUrl()):?>
       <img src="<?php echo $_imageUrl?>" alt="<?php echo $this->getCurrentCategory()->getName();?>" width="100" height="100">
                                    <?php else:?>
    <img src="<?php echo $this->getSkinUrl('images/add-01.gif')?>" alt="<?php echo $this->getCurrentCategory()->getName();?>">
                                    <?php endif;?>
                                    </a>
                                </div>
                            </div>
                        </div>
                        <div class="cat-box-text">
                            <span><a href="<?php echo $this->getCurrentCategory()->getUrl()?>"><?php echo $this->getCurrentCategory()->getName();?></a></span><br>
                            <?php echo $this->getCurrentCategory()->getDescription() ?>
                        </div>
                    </div>
<?php
         endforeach;
            endforeach;
        endforeach;

endif;
?>



Now go to app/code/core/Mage/Catalog/Model/category.php
and add the function:

public function getThumbnailImageUrl()
   {
      $url = false;

      if ($image = $this->getThumbnail()) {

         $url = Mage::getBaseUrl('media').'catalog/category/'.$image;
      }
      return $url;
   }


Now make a cms page and call the phtml file as:
{{block type="catalog/navigation" name="catalog.categories" template="catalog/navigation/category_listing.phtml"}}



Note: This will shows upto 3-level categories in magento

Friday 19 April 2013

Add the Google Checkout botton in the checkout page in magento

Open the app/design/frontend/base/default/template/checkout/onepage/payment.phtml

add this code after <img> tag:
<?php echo $this->getLayout()->createBlock('googlecheckout/link')->setTemplate('googlecheckout/link.phtml')->toHtml(); ?>

Auto generated SKU when add product in magento


Open /app/design/adminhtml/default/default/template/catalog/product/edit.phtml and add the following code to the bottom of the file:

<?php
    $dbread = Mage::getSingleton('core/resource')->getConnection('core_read');
    $sql = $dbread->query("SELECT * FROM catalog_product_entity ORDER BY created_at DESC LIMIT 1");
    $res = $sql->fetch();
?>
<script type="text/javascript">
if(document.getElementById('sku').value == ""){
    document.getElementById('sku').value = <?php echo (int)$res["sku"] + 1; ?>;
}
</script>


Note:Read the SKU (must be an integer) of the last added product.
     Increment the SKU by 1.
     Pre-populate the incremented new SKU to the SKU field by JavaScript.

Thursday 18 April 2013

Making default of product attributes like is_active,tax class, weight,status,stock,qty in magento


UPDATE `eav_attribute` SET `default_value` = 'container1' WHERE `eav_attribute`.`attribute_code`='options_container';
UPDATE `eav_attribute` SET `default_value` = '1' WHERE `eav_attribute`.`attribute_code`='is_active';
UPDATE `eav_attribute` SET `default_value` = '1' WHERE `eav_attribute`.`attribute_code`='is_anchor';
UPDATE `eav_attribute` SET `default_value` = '1' WHERE `eav_attribute`.`attribute_code`='status';
UPDATE `eav_attribute` SET `default_value` = '0' WHERE `eav_attribute`.`attribute_code`='weight';
UPDATE `eav_attribute` SET `default_value` = '2' WHERE `eav_attribute`.`attribute_code`='tax_class_id';
insert into core_config_data values ( null, 'default', 0, 'cataloginventory/item_options/is_in_stock', 1 );
insert into core_config_data values ( null, 'default', 0, 'cataloginventory/item_options/qty', 10 );

Wednesday 17 April 2013

How to use negative discount amount in magento

Step 1: Go to there and comment the line:


app/code/core/Mage/Rule/Model-------->Abstract.php


if ((int)$this->getDiscountAmount() < 0) {
Mage::throwException(Mage::helper(‘rule’)->__(‘Invalid discount amount.’));
}



Step 2: Go here and commented the below line:

app/code/core/Mage/Adminhtml/Block/Promo/Quote/Edit/Tab------->Actions.php


‘class’ => ‘validate-not-negative-number’,

Saturday 13 April 2013

Update products price and special price with sku-simple script in magento

I am searching with this topic but all I find the paid extension for bulk product updation of price. so I made a simple script to update the product with special price and price through their respective sku.

<?php
/**
 * @author      MagePsycho <info@magepsycho.com>
 * @website     http://www.magepsycho.com
 * @category    Export / Import
 */
$mageFilename = 'app/Mage.php';
require_once $mageFilename;
Mage::setIsDeveloperMode(true);
ini_set('display_errors', 1);
umask(0);
Mage::app('admin');
Mage::register('isSecureArea', 1);
Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);

set_time_limit(0);
ini_set('memory_limit','1024M');

/***************** UTILITY FUNCTIONS ********************/
function _getConnection($type = 'core_read'){
    return Mage::getSingleton('core/resource')->getConnection($type);
}

function _getTableName($tableName){
    return Mage::getSingleton('core/resource')->getTableName($tableName);
}

function _getAttributeId($attribute_code = 'price'){
    $connection = _getConnection('core_read');
    $sql = "SELECT attribute_id
                FROM " . _getTableName('eav_attribute') . "
            WHERE
                entity_type_id = ?
                AND attribute_code = ?";
    $entity_type_id = _getEntityTypeId();
    return $connection->fetchOne($sql, array($entity_type_id, $attribute_code));
}
function _getAttributeId1($attribute_code = 'special_price'){
    $connection = _getConnection('core_read');
    $sql = "SELECT attribute_id
                FROM " . _getTableName('eav_attribute') . "
            WHERE
                entity_type_id = ?
                AND attribute_code = ?";
    $entity_type_id1 = _getEntityTypeId();
    return $connection->fetchOne($sql, array($entity_type_id1, $attribute_code));
}

function _getEntityTypeId($entity_type_code = 'catalog_product'){
    $connection = _getConnection('core_read');
    $sql        = "SELECT entity_type_id FROM " . _getTableName('eav_entity_type') . " WHERE entity_type_code = ?";
    return $connection->fetchOne($sql, array($entity_type_code));
}

function _getIdFromSku($sku){
    $connection = _getConnection('core_read');
    $sql        = "SELECT entity_id FROM " . _getTableName('catalog_product_entity') . " WHERE sku = ?";
    return $connection->fetchOne($sql, array($sku));

}


function _checkIfSkuExists($sku){
    $connection = _getConnection('core_read');
    $sql        = "SELECT COUNT(*) AS count_no FROM " . _getTableName('catalog_product_entity') . " WHERE sku = ?";
    $count      = $connection->fetchOne($sql, array($sku));
    if($count > 0){
        return true;
    }else{
        return false;
    }
}

function _updatePrices($data){
    $connection     = _getConnection('core_write');
    $sku            = $data[0];
    $newPrice       = $data[1];
 $specialPrice   = $data[2];
    $productId      = _getIdFromSku($sku);
    $attributeId    = _getAttributeId();
 $attributeId1    = _getAttributeId1();

    $sql = "UPDATE " . _getTableName('catalog_product_entity_decimal') . " cped
                SET  cped.value = ?
            WHERE  cped.attribute_id = ?
            AND cped.entity_id = ?";
$sql1 = "UPDATE " . _getTableName('catalog_product_index_price') . " cpip
                SET  cpip.final_price = ?
            WHERE cpip.entity_id = ?";


    $connection->query($sql, array($newPrice, $attributeId, $productId));
 $connection->query($sql, array($specialPrice, $attributeId1, $productId));
 $connection->query($sql1, array($specialPrice, $productId));

}

/***************** UTILITY FUNCTIONS ********************/

$csv                = new Varien_File_Csv();
$data               = $csv->getData('var/import/prices.csv'); //path to csv
array_shift($data);

$message = '';
$count   = 2;
foreach($data as $_data){
    if(_checkIfSkuExists($_data[0])){
        try{
            _updatePrices($_data);
            $message .= $count . '> Success:: While Updating Price (' . $_data[1] . ') of Sku (' . $_data[0] . '). <br />';
_updatePrices($_data);
            $message .= $count . '> Success:: While Updating Price (' . $_data[2] . ') of Sku (' . $_data[0] . '). <br />';

        }catch(Exception $e){
            $message .=  $count .'> Error:: While Upating  Price (' . $_data[1] . ') of Sku (' . $_data[0] . ') => '.$e->getMessage().'<br />';
$message .=  $count .'> Error:: While Upating  Price (' . $_data[2] . ') of Sku (' . $_data[0] . ') => '.$e->getMessage().'<br />';
        }
    }else{
        $message .=  $count .'> Error:: Product with Sku (' . $_data[0] . ') does\'t exist.<br />';
    }
    $count++;
}
echo $message;
?>




save this script to your root file and run it...
and for csv your field should be:

sku    price   special_price



The csv save in var/import/prices.csv

Note:- prices.csv is the name of csv file.