Pages

Thursday, October 10, 2013

How to delete Magento order programmatically

Unfortunately, there is no way in Magento to delete the orders from Magento store.
You can only process and set status as "Cancelled" of these orders but you can’t really delete those orders from your Magento store.
In order to delete these orders, you have to log in to your PhpmyAdmin and run some queries to get rid of those orders.

Delete a single order:

You need to run the following query on your database:

  set @increment_id='00000111';
  select @order_id:=entity_id from prefix_sales_order_entity where increment_id=@increment_id;
  delete from prefix_sales_order_entity where entity_id=@order_id or parent_id=@order_id;
  delete from prefix_sales_order where increment_id=@increment_id;
 
In the above example, we deleted order '#00000111'. Generally people use prefix to database tables, so change the "prefix_" in the above query with the prefix you have chosen for your store.

Delete all Magento orders:

You need to run the following query on your database:
 
  SET FOREIGN_KEY_CHECKS=0;

  TRUNCATE `sales_order`;
  TRUNCATE `sales_order_datetime`;
  TRUNCATE `sales_order_decimal`;
  TRUNCATE `sales_order_entity`;
  TRUNCATE `sales_order_entity_datetime`;
  TRUNCATE `sales_order_entity_decimal`;
  TRUNCATE `sales_order_entity_int`;
  TRUNCATE `sales_order_entity_text`;
  TRUNCATE `sales_order_entity_varchar`;
  TRUNCATE `sales_order_int`;
  TRUNCATE `sales_order_text`;
  TRUNCATE `sales_order_varchar`;
  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 `sendfriend_log`;
  TRUNCATE `tag`;
  TRUNCATE `tag_relation`;
  TRUNCATE `tag_summary`;
  TRUNCATE `wishlist`;
  TRUNCATE `log_quote`;
  TRUNCATE `report_event`;

  ALTER TABLE `sales_order` AUTO_INCREMENT=1;
  ALTER TABLE `sales_order_datetime` AUTO_INCREMENT=1;
  ALTER TABLE `sales_order_decimal` AUTO_INCREMENT=1;
  ALTER TABLE `sales_order_entity` AUTO_INCREMENT=1;
  ALTER TABLE `sales_order_entity_datetime` AUTO_INCREMENT=1;
  ALTER TABLE `sales_order_entity_decimal` AUTO_INCREMENT=1;
  ALTER TABLE `sales_order_entity_int` AUTO_INCREMENT=1;
  ALTER TABLE `sales_order_entity_text` AUTO_INCREMENT=1;
  ALTER TABLE `sales_order_entity_varchar` AUTO_INCREMENT=1;
  ALTER TABLE `sales_order_int` AUTO_INCREMENT=1;
  ALTER TABLE `sales_order_text` AUTO_INCREMENT=1;
  ALTER TABLE `sales_order_varchar` AUTO_INCREMENT=1;
  ALTER TABLE `sales_flat_quote` AUTO_INCREMENT=1;
  ALTER TABLE `sales_flat_quote_address` AUTO_INCREMENT=1;
  ALTER TABLE `sales_flat_quote_address_item` AUTO_INCREMENT=1;
  ALTER TABLE `sales_flat_quote_item` AUTO_INCREMENT=1;
  ALTER TABLE `sales_flat_quote_item_option` AUTO_INCREMENT=1;
  ALTER TABLE `sales_flat_order_item` AUTO_INCREMENT=1;
  ALTER TABLE `sendfriend_log` AUTO_INCREMENT=1;
  ALTER TABLE `tag` AUTO_INCREMENT=1;
  ALTER TABLE `tag_relation` AUTO_INCREMENT=1;
  ALTER TABLE `tag_summary` AUTO_INCREMENT=1;
  ALTER TABLE `wishlist` AUTO_INCREMENT=1;
  ALTER TABLE `log_quote` AUTO_INCREMENT=1;
  ALTER TABLE `report_event` AUTO_INCREMENT=1;

  -- lets reset customers
  TRUNCATE `customer_address_entity`;
  TRUNCATE `customer_address_entity_datetime`;
  TRUNCATE `customer_address_entity_decimal`;
  TRUNCATE `customer_address_entity_int`;
  TRUNCATE `customer_address_entity_text`;
  TRUNCATE `customer_address_entity_varchar`;
  TRUNCATE `customer_entity`;
  TRUNCATE `customer_entity_datetime`;
  TRUNCATE `customer_entity_decimal`;
  TRUNCATE `customer_entity_int`;
  TRUNCATE `customer_entity_text`;
  TRUNCATE `customer_entity_varchar`;
  TRUNCATE `log_customer`;
  TRUNCATE `log_visitor`;
  TRUNCATE `log_visitor_info`;

  ALTER TABLE `customer_address_entity` AUTO_INCREMENT=1;
  ALTER TABLE `customer_address_entity_datetime` AUTO_INCREMENT=1;
  ALTER TABLE `customer_address_entity_decimal` AUTO_INCREMENT=1;
  ALTER TABLE `customer_address_entity_int` AUTO_INCREMENT=1;
  ALTER TABLE `customer_address_entity_text` AUTO_INCREMENT=1;
  ALTER TABLE `customer_address_entity_varchar` AUTO_INCREMENT=1;
  ALTER TABLE `customer_entity` AUTO_INCREMENT=1;
  ALTER TABLE `customer_entity_datetime` AUTO_INCREMENT=1;
  ALTER TABLE `customer_entity_decimal` AUTO_INCREMENT=1;
  ALTER TABLE `customer_entity_int` AUTO_INCREMENT=1;
  ALTER TABLE `customer_entity_text` AUTO_INCREMENT=1;
  ALTER TABLE `customer_entity_varchar` AUTO_INCREMENT=1;
  ALTER TABLE `log_customer` AUTO_INCREMENT=1;
  ALTER TABLE `log_visitor` AUTO_INCREMENT=1;
  ALTER TABLE `log_visitor_info` AUTO_INCREMENT=1;

  -- Now, lets Reset all ID counters
  TRUNCATE `eav_entity_store`;
  ALTER TABLE  `eav_entity_store` AUTO_INCREMENT=1;

  SET FOREIGN_KEY_CHECKS=1;

Thursday, October 3, 2013

How to get currency code in Magento

We know Magento support multiple currency. Use following code given below to check current currency in the Magento site frontend.

To get current currency code

<?php echo $current_currency_code = Mage::app()->getStore()->getCurrentCurrencyCode(); ?>

If you looking for current currency symbol use :

<?php echo Mage::app()->getLocale()->currency(Mage::app()->getStore()->getCurrentCurrencyCode())->getSymbol(); ?>

Tuesday, October 1, 2013

How to show out of stock products to the end of the product list in Magento

First of all overwrite the file

app/code/core/Mage/Catalog/Model/Layer.php

and copy this file to

app/code/local/Mage/Catalog/Model/Layer.php

In function getProductCollection(), Put this code after line #102

<?php
$collection->joinField('inventory_in_stock', 'cataloginventory_stock_item', 'is_in_stock', 'product_id=entity_id','is_in_stock>=0', 'left')->setOrder('inventory_in_stock', 'desc');
?>

Tuesday, September 10, 2013

How to add categories to product by product sku programmatically in Magento

<?php

$rootDir = ""; //root path
include($rootDir."app/Mage.php");
Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
Mage::app("default");
$baseUrl = Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_WEB);

// $productsSkus is an array of the products you want to modify.
// Create it however you want, I did it like this...
$productsSkus = array('100246','800649','017261','006403');

//update product categories
for($i=0;$i<count($productsSkus);$i++)
{
$productModel = Mage::getModel('catalog/product');
$productId = $productModel->getIdBySku($productsSkus[$i]);
$product = $productModel->load($productId);
$categoryArr = $product->getCategoryIds();
// Array of category_ids to add.
$categoryArr[] = 842;
$product->setCategoryIds(array($categoryArr));
$product->save();

}
?>
Hope you will enjoy!

Thursday, September 5, 2013

How to get customer name, customer email on success.phtml/order confirmation page in Magento

<?php
$order = Mage::getModel('sales/order')->loadByIncrementId($orderId);
if($order->getCustomerId() === NULL)
{
$customerName  = $order->getBillingAddress()->getName();
$customerEmail = $order->getBillingAddress()->getEmail();
}
else
{
$customer      = Mage::getModel('customer/customer')->load($order->getCustomerId());
$customerName  = $order->getCustomerName();
$customerEmail = $order->getCustomerEmail();
}
?>

Wednesday, September 4, 2013

How to get total quantity of product sold in Magento

<?php
$id = 100001; // Enter your product ID here
$_productCollection = Mage::getResourceModel('reports/product_collection')
    ->addOrderedQty()
    ->addAttributeToFilter('id', $id)
    ->setOrder('ordered_qty', 'DESC')
    ->getFirstItem();
$product = $_productCollection;
echo 'Total Sold'.$product->ordered_qty;
?>

Sunday, September 1, 2013

How to disable Google Checkout button in Magento

Use the following steps to disable google checkout button from cart page as given below:

Login into Admin first then

Steps 1: Go to System->Configuration

Steps 2: Click on "Gopple API" under "Sales Tab" from left side.

Steps 3: Click on "Google Checkout" and select Enable "No".

Steps 4: Click on "Save Config" button at the top.

Wednesday, August 28, 2013

Sort products by 2 attributes in magento

Sort products by 2 attributes in magento

In magento site suppose you have the requirement to sort the product listings by 2 attributes like "in stock" and "popularity"

After some research, it seems to work.

Use the following code given below:

<?php
     $Collection->setOrder(array('attribute1', 'attribute2'), asc); //the setOrder() method accepts an array.
?>

Modified this line in Toolbar.php in the Catalogue/Product/List/ directory.

<?php
 if ($this->getCurrentOrder())
 {
    $this->_collection->setOrder(array($this->getCurrentOrder(), 'in stock'), $this->getCurrentDirection());
 }
?>

Hope this will work!




Monday, August 26, 2013

Enable template path hint in Magento

To enable magento path hint for your magento website

Login into admin section and go to System->Configuration->Advanced->Developer

Inside this, click on "Debug" option.

If the Current Configuration Scope is "Default" (left top), you will be not able to set template path hints for your magento website.

So you have to select the magento website from the dropdown and then change the template Path Hints to "yes" .

Now your template path hint has been enabled. You can view template path hint on the frontend of your website.

if some how due to cache you are not getting the path hint.

Then go to System->Cache management and "flush" or "refresh" the cache.

Friday, August 23, 2013

Magento: Difference between order states and statuses

If you are building website in Magento, you may have noticed that there are two columns insales_flat_order table which are confusing. These are state and status. You might think what is the difference between these two, both having same meaning.

Well, this is not the case. They both are different. State is used by magento to tell if the order is new, processing, complete, holded, closed, canceled, etc.; while Statuses are the one that YOU would be defining at the backend in System -> Order Statuses. Magento displays order STATUSES and not STATES in the backend order detail page to let you know which status is assigned as per your mapping. Remember, multiple statuses can be mapped with one state, while vice versa is not possible.

Consider an example, your customer places an order as Cash on Delivery, you will need something like COD_Pending as the order status so that you know it is not yet paid. Magento will have state new for this, which makes you unpredictable of what kind of transaction is this, COD or Prepaid. The STATUS can be anything, as you define, for your understanding; while STATE is something which Magento needs to understand, internally.

In short, Magento uses order state internally for processing order, whereas order status are used by store owners to understand the exact order flow where one state can be assigned to multiple statuses.

To understand this in detail, have a look at this

Thursday, August 22, 2013

How to create categories tree structure in Magento programmatically

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

<?php

set_time_limit(0);
error_reporting(E_ALL ^ E_NOTICE);
ini_set("display_errors",'On');

$rootDir = ""; // Root Directory Path
include($rootDir."app/Mage.php");
Mage::app("default");

$rootcatId= Mage::app()->getStore()->getRootCategoryId(); // get default store root category id
$categories = Mage::getModel('catalog/category')->getCategories($rootcatId); // else use default category id =2

function  show_categories_tree($categories) {
    $array= '<ul>';
    foreach($categories as $category) {
        $cat = Mage::getModel('catalog/category')->load($category->getId());
        $count = $cat->getProductCount();
        $array .= '<li>'.
        '<a href="' . Mage::getUrl($cat->getUrlPath()). '">' .
                  $category->getName() . "(".$count.")</a>\n";
        if($category->hasChildren()) {
            $children = Mage::getModel('catalog/category')->getCategories($category->getId());
             $array .=  show_categories_tree($children);
            }
         $array .= '</li>';
    }
    return  $array . '</ul>';
}
echo  show_categories_tree($categories);

?>

Wednesday, August 21, 2013

How to add/update category in magento from csv programmatically

<?php
set_time_limit(0);
ini_set(‘memory_limit’,’1024M’);
require_once ‘../../app/Mage.php’;
Mage::app();

//read data from csv file
$row = 1; $cat_arr = array();
if (($handle = fopen(“category.csv”, “r”)) !== FALSE)
{
while (($data = fgetcsv($handle, 100000, “,”)) !== FALSE)
{
if($row > 1)
{

/* $data[0] is csv column in csv file
$data[1],$data[2],$data[3],$data[4] is category Id column */

$cat_arr[trim($data[0])] = $data[1].”,”.$data[2].”,”.$data[3].”,”.$data[4].”,”.$data[5].”,”.$data[6].”,”.$data[7]; // $data[0] column represent sku

}

$row++;
}
fclose($handle);
}

$products = Mage::getResourceModel(‘catalog/product_collection’);
$i = 1 ;
foreach ( $products as $index => $productModel )
{
$_product = Mage::getModel(‘catalog/product’)->load($productModel->getId());
$cnids = $cat_arr[$_product->getSku()];
$ids = explode(“,”,$cnids);
$_product->setCategoryIds($ids);
$_product->save();
$i++;
}

?>

How to call category list in footer in magento

<?php $helper = $this->helper('catalog/category') ?>

<?php foreach ($helper->getStoreCategories() as $_category): ?>
<a href="<?php echo Mage::getModel('catalog/category')                                                                                                                                                                                                                                                                                            ->setData($_category->getData())->getUrl(); ?>" title="<?php echo $_category->getName() ?>">   <?php echo $_category->getName() ?></a>
<?php endforeach ?>

How to Add related products in Magento by code / script

To create the related product programmatically in Magento

<?php
set_time_limit(0);
ini_set(‘memory_limit’,’1024M’);
require_once ‘../../app/Mage.php’;
Mage::app();

$sku=’12345’;  //some Sku
$product = Mage::getModel(‘catalog/product’)->loadByAttribute(‘sku’,$sku);

if($product){
$sRelatedProducts = "123456,123";
$aRelatedProducts = explode(‘,’, $sRelatedProducts);  // or other way to get the array of related product sku

$aParams = array();
$nRelatedCounter = 1;
$aProduct    = Mage::getModel(‘catalog/product’)->loadByAttribute(‘sku’, $sku);
$aMainProduct = Mage::getModel(‘catalog/product’);
$aMainProduct->load($aProduct['entity_id']);

foreach($aRelatedProducts as $sSku)
{
$aRelatedProduct = Mage::getModel(‘catalog/product’)->loadByAttribute(‘sku’, $sSku);

$aParams[$aRelatedProduct['entity_id']] = array(
‘position’     => $nRelatedCounter
);

$nRelatedCounter++;
}

$product->setRelatedLinkData($aParams);
$product->save();
}

echo “Great!!”;

?>

How to Override controller in magento / Override controller’s action in magento

Requirement : Some times you may run into situation where you want to override the core functionality of Magento core controllers. So in this case, The best practise is override the controller then override actions or add new actions for custom requirement.

For example you want to override OnepageController.php file and overwride indexAction.

In this example my custom module name space is “MyBlog” and i am going to overwride indexAction Mage_Checkout_OnepageController

Base File Path : app/code/core/Mage/Checkout/controllers/OnepageController.php

To Do the same we have to follow bellow steps.

Step1: We need to create a custom module

File Path : app/etc/modules/

File Name: MyBlog_Checkout.xml

File Content:

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

Step2: Now we have to create bellow files in our custom module

File Path: app/code/local/MyBlog/Checkout/etc/config.xml

Bellow is content for config.xml file

<?xml version="1.0"?>
<config>
     <modules>
       <MyBlog_Checkout>
         <version>0.0.1</version>
       </MyBlog_Checkout>
     </modules>

    <frontend>
        <routers>
            <checkout>
                <args>
                    <modules>
                        <MyBlog_Checkout before="Mage_Checkout">MyBlog_Checkout</MyBlog_Checkout>
                    </modules>
                </args>
            </checkout>
        </routers>
    </frontend>
</config>

Bellow is content for OnepageController.php

File Path : app/code/local/MyBlog/Checkout/controllers/OnepageController.php

<?php
 
require_once 'Mage/Checkout/controllers/OnepageController.php';
class MyBlog_Checkout_OnepageController extends Mage_Checkout_OnepageController {

     public function indexAction()
    {
        echo "Great! You are in MyBlog checkout controller section";
        exit;
    }

}
?>

Monday, August 19, 2013

How to delete a quote in Magento

Use the code below to delete a quote:

<?php
$quoteID = Mage::getSingleton("checkout/session")->getQuote()->getId();

if($quoteID)
{
    try {
        $quote = Mage::getModel("sales/quote")->load($quoteID);
        $quote->setIsActive(false);
        $quote->delete();

        return "cart deleted";
    } catch(Exception $e) {
        return $e->getMessage();
    }
}else{
    return "no quote found";
}

How to get shipping and handling cost, tax, discount in magento on shopping cart page

We can simply use the following code

// To get the shipping and handling charge on shopping cart page

Mage::getSingleton('checkout/session')->getQuote()->getShippingAddress()->getShippingAmount();

 // To get discount and tax  on shopping cart page

$totals = Mage::getSingleton('checkout/session')->getQuote()->getTotals(); //Total object

 // To get the discount
if(isset($totals['discount']) && $totals['discount']->getValue()) {
echo 'Discount :'. $discount = $totals['discount']->getValue(); //Discount value if applied
} else {
$discount = '';
}

 // To get tax
if(isset($totals['tax']) && $totals['tax']->getValue()) {
echo 'Tax :'.$tax = $totals['tax']->getValue(); //Tax value if present
} else {
$tax = '';
}

Sunday, August 18, 2013

Create Catalog Price Rule Programmatically in Magento

Here, you will see how to create Catalog Price Rule in Magento through code.

Catalog Rules are applied on products before they are added to the cart.

To create a Catalog Price Rule from Admin Panel, we go to Promotions -> Catalog Price Rules and select Add New Rule.

Basically, there are three main parts for Catalog Price Rule, i.e. Rule Information, Conditions, and Actions.

Here is the code to create Catalog Price Rule. In this code example, I have created Catalog Price Rule with the following information:-

- The rule is applied to particular product with the particular SKU (in our case: ‘chair’)
- The rule is applied as Fixed Amount Discount To certain amount (in our case: 20) of currency amount

$name = "My Catalog Price Rule"; // name of Catalog Price Rule
$websiteId = 1;
$customerGroupId = 2;
$actionType = 'to_fixed'; // discount to fixed amount
//(other options are: by_fixed, by_percent, to_percent)
$discount = 20; // discount amount
$sku = 'chair'; // product sku

$catalogPriceRule = Mage::getModel('catalogrule/rule');

$catalogPriceRule->setName($name)
                 ->setDescription('')
                 ->setIsActive(1)
                 ->setWebsiteIds(array($websiteId))
                 ->setCustomerGroupIds(array($customerGroupId))
                 ->setFromDate('')
                 ->setToDate('')
                 ->setSortOrder('')
                 ->setSimpleAction($actionType)
                 ->setDiscountAmount($discount)
                 ->setStopRulesProcessing(0);

$skuCondition = Mage::getModel('catalogrule/rule_condition_product')
                    ->setType('catalogrule/rule_condition_product')
                    ->setAttribute('sku')
                    ->setOperator('==')
                    ->setValue($sku);

try {
    $catalogPriceRule->getConditions()->addCondition($skuCondition);
    $catalogPriceRule->save();
    $catalogPriceRule->applyAll();
} catch (Exception $e) {
    Mage::getSingleton('core/session')->addError(Mage::helper('catalog')->__($e->getMessage()));
    return;
}

A new Catalog Price Rule with the name “My Catalog Price Rule” has been created. You can view the rule from Promotions -> Catalog Price Rules in admin.

Thursday, August 15, 2013

How to move top links in Content in Magento

If local.xml does not exist,create it /you_theme/layout/ and add the following code Ctalog.xml
{{block type=”catalog/navigation” name=”catalog.topnav” template=”catalog/navigation/top.phtml”}}

Wednesday, August 14, 2013

Get creditcard type in Magento

$order_id = 100; //order id goes here
$_order = Mage::getModel('sales/order')->load($order_id);      
$_cctype = '';
if(!empty($_order))
{          
    $_cctype = $_order->getPayment()->getCcTypeName();
}
echo $_cctype;

Remove Top Links in Magento

Just comment the top link block in the layout file

My Account
/app/design/frontend/Your-Interface/Your-Theme/layout/customer.xml

My cart and Checkout
/app/design/frontend/Your-Interface/Your-Theme/layout/checkout.xml

My Wishlist
/app/design/frontend/Your-Interface/Your-Theme/layout/wishlist.xml

To Display The Currency In Frontend in Magento

Currency In Dropdown format

In page.xml add the Block if not exist

<block type=”directory/currency” name=”currency” as=”currency” template=”directory/currency.phtml”/>

Template File

/app/design/frontend/template/Your_Interface/YOUR-TEMPLATE-NAME/template/directory/currency.phtml

To get the Currency Symbol in front end

<?php if($this->getCurrencyCount()>1): ?>

<?php foreach ($this->getCurrencies() as $_code => $_name): ?>

<?php echo Mage::app()->getLocale()->currency($_code)->getSymbol();?>

<?php endforeach; ?>

<?php endif; ?>

How to create Magento Module

In this tutorial, we will introduce the coding of Magento in the form of a “Hello World”-style module. The goal of the module will be simply to write some information to a log file every time a product is saved. This very basic module will allow us to cover a number of interesting topics, including:
The app/code directories,
The structure and creation of a Magento module,
Event observers,
Logging.
Before We Begin

This tutorial assumes that you already have an installation of Magento up and running, either locally or on a development server, that you can add new files to. The version of Magento that you use doesn’t really matter, because we will be covering fundamental aspects that exist across all versions and editions: Community, Professional and Enterprise.
Disable the Cache

This is one of the first lessons a Magento developer should learn: disable the cache! You can do this by going to Admin Panel > System > Cache Management > Select All > Actions: Disable > Submit.
While very good at boosting performance in a production environment, the cache is a developer’s enemy. Leave it enabled at your peril! Every Magento developer I have met has on more than one occasion spent an hour or so wondering why their latest update is not showing up, only to find that Magento is still displaying the version of the website that it conveniently cached earlier that day.
The app/code Directory

How to create Magento mobile site

Recent studies have shown that in the near future (by 2014) more people will use mobile devices ( iPod, iPhone, Tablet …) rather than computers, which can be a problem for the advancement of your business. Magento offers you an ideal solution how to overcome that problem. This tutorial will help you to install a mobile theme on your web site.
You can quickly and very easily create a storefront, which is suitable for mobile devices, so users can shop even when they aren´t near their computers.
Magento 1.7  uses HTML5 technology, which is supported by iPhone , Android, Opera Mini, iPod, Blackberry and many more.
HTML5 technology includes many out-of-the-box features, which give you many advantages such as:
• Specific video and audio media capabilities
• Simple search and results display
• Your display will be clean of product detail pages
• Swiping product images is very easy
• You can zoom in and zoom out
• Cross-sell and up-sell capabilities
• Drag-and-drop capabilities
If you want to activate the HTML5 mobile theme for Magento 1.7, you need to follow these instructions. There are only four steps in how to setup a mobile theme on your web site.


How to remove Shop by Options from the left bar in magento

In Catalog.xml

Please Comment following code
<!--<reference name="left"><block type="catalog/layer_view" name="catalog.leftnav" after="currency" template="catalog/layer/view.phtml"/>
</reference>
-->

Sunday, August 11, 2013

To Change The Default Magento Logo

In ADMIN end
System -> Configuration->General->Design
Click on “Design” in the left side menu and open the “Header” section
Change the file name in the “Logo Image Src” to the file name you just uplaoded.Here you can also change the logo Alt message

Get Connection & Custom Query Execution in Magento

For database connection
$write = Mage::getSingleton('core/resource')->getConnection('core_write');

$qry=”Select * from tablename”;
$execute=$write->query($qry);
$fetch=$execute->fetch()
To get the Row Count
$count=$execute->rowCount();

Get Magento Urls in Phtml Page

Get Base Url :
Mage::getBaseUrl();
Get Store Url : 
Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_WEB);
Get Skin Url :
Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_SKIN);
$this->getSkinUrl(‘images/imagename.jpg’);
Get Media Url :
Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_MEDIA);
Get Js Url : 
Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_JS);
Get Current Url
Mage::helper(‘core/url’)->getCurrentUrl();
Get Home Url
Mage::helper(‘core/url’)->getHomeUrl();

Get Urls in Cms Pages or Static Blocks in Magento

Get Base Url :
{{store url=”"}}
Get Skin Url :
{{skin url=’images/imagename.jpg’}}
Get Media Url :
{{media url=’/imagename.jpg’}}
Get Store Url : 
{{store url=’mypage.html’}}

How to Call Magento Static Block in CMS Page and phtml in Magento

In PHTML
<?php echo $this->getLayout()->createBlock(‘cms/block’)->setBlockId(‘yourblockid’)->toHtml(); ?>
IN CMS
{{block type=”cms/block”  block_id=”yourblockid“}}

Get Top 10 Products in Magento

$collection= Mage::getResourceModel('catalog/product_collection')
->addAttributeToSelect('*')
->setStoreId($storeId)
->addStoreFilter($storeId)

->setOrder(‘ordered_qty’, ’desc’)
->setPageSize(10) ;
foreach($collection as $product)
{
$name=$product->getName();
$productId=$product->getId();
$price=$product->getPrice();
}

Get Customer Details Using Customer Session in Magento

$customer = Mage::getSingleton(‘customer/session’)->getCustomer();
$email = $customer->getEmail(); // To get Email Address of a customer.
$firstname = $customer->getFirstname(); // To get Firstname of a customer.
$lastname= $customer->getLastname(); // To get Lastname of a customer.
$id =$customer->getId(); // To get Customer Id
//Get Details Using Customer Id
$customer = Mage::getModel(‘customer/customer’)->load($id)->getData();

Get Current Category Id in Magento

$layer = Mage::getSingleton(‘catalog/layer’);
$_category = $layer->getCurrentCategory();
$currentCategoryId= $_category->getId();

How do I remove Grid view or List view from my Magento store?

System->Configuration->Catalog->Frontend
You can change the List Mode.

Remove other shipping if Free shipping available in magento

//To get the subtotal in shipping method (onepage checkout)
$subtotal = Mage::getSingleton(‘checkout/session’)->getQuote()->getSubtotal()
If cart total is less than 500 flat rate will enabled and free shipping will be disabled , for this
app/design/frontend/Your-Namespace /MODULE/template/checkout/onepage/shipping_method/available.phtml
<?php
if($subtotal >=500)
{
// Remove any other shipping methods if free shipping is available
if (array_key_exists(‘freeshipping’, $_shippingRateGroups )) {
$_shippingRateGroups = array(‘freeshipping’ => $_shippingRateGroups['freeshipping']);
}
}
?>

Tuesday, August 6, 2013

Stock Status Index process is working now. Please try run this process later in magento

Delete the locks files from var/locks or Delete var folder and create it again and give 777 premission
then tried again reindexing problem is solved.

Authorized.net Gateway error: (TESTMODE) The merchant login ID or password is invalid or the account is inactive in magento

Create test account and use
Go do  Magento Dashboard:
  1. Go to System -> Configuration
  2. Select Sales -> Payment Method (in the left sidebar)
  3. Expand the “Authorize.net
  4. Change the “Gateway URL” to https://test.authorize.net/gateway/transact.dll
  5. Click “Save Config” at the top.

How to call a phtml file from controller in magento



<?php
class Namespace_Module_DisplayController extends Mage_Core_Controller_Front_Action
{
public function popupAction()
{
$block = $this->getLayout()->createBlock(‘core/template’)
->setTemplate(‘zipcode/popup.phtml’);
$this->getResponse()->setBody(
$block->toHtml()
);
}
}

How to get the admin frontend name in magento

By default the magento admin path is ‘http://Yourwemsite/admin&#8217;. You  change this name (admin)  with any name  while installing. To get the adminFrontName use the following.
$adminFrontName = (string)Mage::getConfig()->getNode(‘admin/routers/adminhtml/args/frontName’);

Get Store Email address in Magento

//General Contact
echo $name = Mage::getStoreConfig('trans_email/ident_general/name'); //sender name
echo $email = Mage::getStoreConfig('trans_email/ident_general/email'); //sender email
//Sales Representative
echo $name = Mage::getStoreConfig('trans_email/ident_sales/name'); //sender name
echo $email = Mage::getStoreConfig('trans_email/ident_sales/email'); //sender email
//Customer Support
echo $name = Mage::getStoreConfig('trans_email/ident_support/name'); //sender name
echo $email = Mage::getStoreConfig('trans_email/ident_support/email'); //sender email
 //Custom Email 1
echo $name = Mage::getStoreConfig('trans_email/ident_custom1/name'); //sender name
echo $email = Mage::getStoreConfig('trans_email/ident_custom1/email'); //sender email
//Custom Email 2
echo $name = Mage::getStoreConfig('trans_email/ident_custom2/name'); //sender name
echo $email = Mage::getStoreConfig('trans_email/ident_custom2/email'); //sender email

Track visitors information in magento

Here, I will show you how to track visitor’s data information in Magento. By visitor’s information, I mean information like remote address, http host, user agent (browser), referer url, first visit date time, last visit date time, etc.
The following code fetches the vistor data:-
$visitorData = Mage::getSingleton('core/session')->getVisitorData();
// printing visitor information data
echo "<pre>"; print_r($visitorData); echo "</pre>";
You will get an array of visitor information data like the following one:-

Array
(
    [] =>
    [server_addr] => 167772437
    [remote_addr] => 167772437
    [http_secure] =>
    [http_host] => 127.0.0.1
    [http_user_agent] => Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/534.10 (KHTML, like Gecko) Chrome/8.0.552.237 Safari/534.10
    [http_accept_language] => en-US,en;q=0.8
    [http_accept_charset] => ISO-8859-1,utf-8;q=0.7,*;q=0.3
    [request_uri] => /magento/index.php/catalog/category/view/id/22
    [session_id] => 13qm5u80238vb15lupqcac97r5
    [http_referer] => http://127.0.0.1/magento/
    [first_visit_at] => 2011-01-17 11:42:23
    [is_new_visitor] =>
    [last_visit_at] => 2011-01-17 11:58:38
    [visitor_id] => 41
    [last_url_id] => 139
)

In the above array, the server_addr and remote_addr are in different form than usual. The (IPv4) Internet Protocol dotted address has been converted into a proper address using ip2long PHP function. You can get the same kind of value from the following code:-
// user's ip address (visitor's ip address)
$remoteAddr = Mage::helper('core/http')->getRemoteAddr(true);
// server's ip address (where the current script is)
$serverAddr = Mage::helper('core/http')->getServerAddr(true);

Hope this helps. Thanks.

How to get the customer login, logout, register and checkout url in magento

Mage::getUrl(‘customer/account/login’); //login url
Mage::getUrl(‘customer/account/logout’); //logout url
Mage::getUrl(‘customer/account’); //My Account url
Mage::getUrl(‘customer/account/create’); // Register url
Mage::getUrl(‘checkout/cart’); //Checkout url

Remove or rename ‘Add New’ button from Admin Grid Magento

Rename ‘Add New’ button

Here are the steps to rename the ‘Add New’ text to anything you required (for example, ‘Add Report’):-
- Go to YourNamespace -> YourModule -> Block -> Adminhtml -> YourFile.php
- Add the following code in the constructor of this file:-

$this->_addButtonLabel = Mage::helper('yourmodulename')->__('Add Report');


Remove ‘Add New’ button

Here are the steps to remove the ‘Add New’ button:-
- Go to YourNamespace -> YourModule -> Block -> Adminhtml -> YourFile.php
- Add the following code in the constructor of this file (it should be just below the call to parent constructor):-

parent::__construct();
$this->_removeButton('add');

Thursday, August 1, 2013

Script to export magento categories

If you are after a quick method to get all the category ID’s for your categories for some Excel lookups (for new data imports), then this quick PHP script should help you out:

<?php

    define('MAGENTO', realpath(dirname(__FILE__)));
    require_once MAGENTO . '/app/Mage.php';
    Mage::app();

    $category = Mage::getModel ( 'catalog/category' );
    $tree = $category->getTreeModel ();
    $tree->load ();
    
    $ids = $tree->getCollection ()->getAllIds ();
    
    if ($ids) {
        $file = "var/import/catwithid.csv";
        file_put_contents($file,"catId, catNamen");
        foreach ( $ids as $id ) {
          $string = $id . ', ' .$category->load($id)->getName() . "n";
            file_put_contents($file,$string,FILE_APPEND);
        }
    }
?>

Generate Category Tree in Magento

<?php
$rootDir = ""; //include root path
include($rootDir."app/Mage.php");
$rootcatId= Mage::app()->getStore()->getRootCategoryId();
$categories = Mage::getModel('catalog/category')->getCategories($rootcatId);
function  get_categories($categories) {
    $array= '<ul>';
    foreach($categories as $category) {
        $cat = Mage::getModel('catalog/category')->load($category->getId());
        $count = $cat->getProductCount();
        $array .= '<li>'.
        '<a href="' . Mage::getUrl($cat->getUrlPath()). '">' .
                  $category->getName() . "(".$count.")</a>\n";
        if($category->hasChildren()) {
            $children = Mage::getModel('catalog/category')->getCategories($category->getId());
             $array .=  get_categories($children);
            }
         $array .= '</li>';
    }
    return  $array . '</ul>';
}
echo  get_categories($categories); ?>

Monday, July 29, 2013

How to create Credit Memo programmatically in magento

Below is a php code to create a credit memo for an order in magento.
$order = Mage::getModel('sales/order')->load('100000001', 'increment_id');
        if (!$order->getId()) {
            $this->_fault('order_not_exists');
        }
        if (!$order->canCreditmemo()) {
            $this->_fault('cannot_create_creditmemo');
        }
        $data = array();

        
        $service = Mage::getModel('sales/service_order', $order);
       
        $creditmemo = $service->prepareCreditmemo($data);

        // refund to Store Credit
        if ($refundToStoreCreditAmount) {
            // check if refund to Store Credit is available
            if ($order->getCustomerIsGuest()) {
                $this->_fault('cannot_refund_to_storecredit');
            }
            $refundToStoreCreditAmount = max(
                0,     min($creditmemo->getBaseCustomerBalanceReturnMax(), $refundToStoreCreditAmount)
            );
            if ($refundToStoreCreditAmount) {
                $refundToStoreCreditAmount = $creditmemo->getStore()->roundPrice($refundToStoreCreditAmount);
                $creditmemo->setBaseCustomerBalanceTotalRefunded($refundToStoreCreditAmount);
                $refundToStoreCreditAmount = $creditmemo->getStore()->roundPrice(
                    $refundToStoreCreditAmount*$order->getStoreToOrderRate()
                );
                // this field can be used by customer balance observer
                $creditmemo->setBsCustomerBalTotalRefunded($refundToStoreCreditAmount);
                // setting flag to make actual refund to customer balance after credit memo save
                $creditmemo->setCustomerBalanceRefundFlag(true);
            }
        }
        $creditmemo->setPaymentRefundDisallowed(true)->register();
        // add comment to creditmemo
        if (!empty($comment)) {
            $creditmemo->addComment($comment, $notifyCustomer);
        }
        try {
            Mage::getModel('core/resource_transaction')
                ->addObject($creditmemo)
                ->addObject($order)
                ->save();
            // send email notification
            $creditmemo->sendEmail($notifyCustomer, ($includeComment ? $comment : ''));
        } catch (Mage_Core_Exception $e) {
            $this->_fault('data_invalid', $e->getMessage());
        }
        echo $creditmemo->getIncrementId();

How to create Shipment programmatically in magento

Below is a php code to create a shipment for an order in magento.

$order = Mage::getModel('sales/order')->loadByIncrementId('100000001');

try {
    if($order->canShip()) {
        //Create shipment
        $shipmentid = Mage::getModel('sales/order_shipment_api')
                        ->create($order->getIncrementId(), array());
        //Add tracking information
        $ship = Mage::getModel('sales/order_shipment_api')
                        ->addTrack($order->getIncrementId(), array());      
    }
}catch (Mage_Core_Exception $e) {
 print_r($e);
}

How to create invoice programmatically in magento

Below is a php code to create invoice for an order in magento.
   
$order = Mage::getModel('sales/order')->loadByIncrementId('100000001');
try {
if(!$order->canInvoice())
{
Mage::throwException(Mage::helper('core')->__('Cannot create an invoice.'));
}
 
$invoice = Mage::getModel('sales/service_order', $order)->prepareInvoice();
 
if (!$invoice->getTotalQty()) {
Mage::throwException(Mage::helper('core')->__('Cannot create an invoice without products.'));
}
 
$invoice->setRequestedCaptureCase(Mage_Sales_Model_Order_Invoice::CAPTURE_ONLINE);
//Or you can use
//$invoice->setRequestedCaptureCase(Mage_Sales_Model_Order_Invoice::CAPTURE_OFFLINE);
$invoice->register();
$transactionSave = Mage::getModel('core/resource_transaction')
->addObject($invoice)
->addObject($invoice->getOrder());
 
$transactionSave->save();
}
catch (Mage_Core_Exception $e) {
 
}

How to create customer programmatically in magento

Below is a php code to create a customer account in magento.

$customer = Mage::getModel('customer/customer');
$password = 'test1234';
$email = 'dtest@gmail.com<script type="text/javascript">
/* <![CDATA[ */
(function(){try{var s,a,i,j,r,c,l,b=document.getElementsByTagName("script");l=b[b.length-1].previousSibling;a=l.getAttribute('data-cfemail');if(a){s='';r=parseInt(a.substr(0,2),16);for(j=2;a.length-j;j+=2){c=parseInt(a.substr(j,2),16)^r;s+=String.fromCharCode(c);}s=document.createTextNode(s);l.parentNode.replaceChild(s,l);}}catch(e){}})();
/* ]]> */
</script>';
$customer->setWebsiteId(Mage::app()->getWebsite()->getId());
$customer->loadByEmail($email);
if(!$customer->getId()) {
    $groups = Mage::getResourceModel('customer/group_collection')->getData();
    $groupID = '3';

    $customer->setData( 'group_id', $groupID );
    $customer->setEmail($email);
    $customer->setFirstname('test');
    $customer->setLastname('testing');
    $customer->setPassword($password);

    $customer->setConfirmation(null);
    $customer->save();

    echo $customer->getId();
}

How to create Order programmatically in magento

Below is the php code to create an order in magento. It requires a valid customer account with shipping and billing address setup.
   
$id=1; // get Customer Id
$customer = Mage::getModel('customer/customer')->load($id);

$transaction = Mage::getModel('core/resource_transaction');
$storeId = $customer->getStoreId();
$reservedOrderId = Mage::getSingleton('eav/config')->getEntityType('order')->fetchNewIncrementId($storeId);

$order = Mage::getModel('sales/order')
->setIncrementId($reservedOrderId)
->setStoreId($storeId)
->setQuoteId(0)
->setGlobal_currency_code('USD')
->setBase_currency_code('USD')
->setStore_currency_code('USD')
->setOrder_currency_code('USD');
//Set your store currency USD or any other

// set Customer data
$order->setCustomer_email($customer->getEmail())
->setCustomerFirstname($customer->getFirstname())
->setCustomerLastname($customer->getLastname())
->setCustomerGroupId($customer->getGroupId())
->setCustomer_is_guest(0)
->setCustomer($customer);



// set Billing Address
$billing = $customer->getDefaultBillingAddress();
$billingAddress = Mage::getModel('sales/order_address')
->setStoreId($storeId)
->setAddressType(Mage_Sales_Model_Quote_Address::TYPE_BILLING)
->setCustomerId($customer->getId())
->setCustomerAddressId($customer->getDefaultBilling())
->setCustomer_address_id($billing->getEntityId())
->setPrefix($billing->getPrefix())
->setFirstname($billing->getFirstname())
->setMiddlename($billing->getMiddlename())
->setLastname($billing->getLastname())
->setSuffix($billing->getSuffix())
->setCompany($billing->getCompany())
->setStreet($billing->getStreet())
->setCity($billing->getCity())
->setCountry_id($billing->getCountryId())
->setRegion($billing->getRegion())
->setRegion_id($billing->getRegionId())
->setPostcode($billing->getPostcode())
->setTelephone($billing->getTelephone())
->setFax($billing->getFax());
$order->setBillingAddress($billingAddress);

$shipping = $customer->getDefaultShippingAddress();
$shippingAddress = Mage::getModel('sales/order_address')
->setStoreId($storeId)
->setAddressType(Mage_Sales_Model_Quote_Address::TYPE_SHIPPING)
->setCustomerId($customer->getId())
->setCustomerAddressId($customer->getDefaultShipping())
->setCustomer_address_id($shipping->getEntityId())
->setPrefix($shipping->getPrefix())
->setFirstname($shipping->getFirstname())
->setMiddlename($shipping->getMiddlename())
->setLastname($shipping->getLastname())
->setSuffix($shipping->getSuffix())
->setCompany($shipping->getCompany())
->setStreet($shipping->getStreet())
->setCity($shipping->getCity())
->setCountry_id($shipping->getCountryId())
->setRegion($shipping->getRegion())
->setRegion_id($shipping->getRegionId())
->setPostcode($shipping->getPostcode())
->setTelephone($shipping->getTelephone())
->setFax($shipping->getFax());

$order->setShippingAddress($shippingAddress)
->setShipping_method('flatrate_flatrate');
/*->setShippingDescription($this->getCarrierName('flatrate'));*/
/*some error i am getting here need to solve further*/

//you can set your payment method name here as per your need
$orderPayment = Mage::getModel('sales/order_payment')
->setStoreId($storeId)
->setCustomerPaymentId(0)
->setMethod('purchaseorder')
->setPo_number(' – ');
$order->setPayment($orderPayment);

// let say, we have 1 product
//check that your products exists
//need to add code for configurable products if any
$subTotal = 0;
$products = array(
    '1' => array(
    'qty' => 2
    )
);

foreach ($products as $productId=>$product) {
$_product = Mage::getModel('catalog/product')->load($productId);
$rowTotal = $_product->getPrice() * $product['qty'];
$orderItem = Mage::getModel('sales/order_item')
->setStoreId($storeId)
->setQuoteItemId(0)
->setQuoteParentItemId(NULL)
->setProductId($productId)
->setProductType($_product->getTypeId())
->setQtyBackordered(NULL)
->setTotalQtyOrdered($product['rqty'])
->setQtyOrdered($product['qty'])
->setName($_product->getName())
->setSku($_product->getSku())
->setPrice($_product->getPrice())
->setBasePrice($_product->getPrice())
->setOriginalPrice($_product->getPrice())
->setRowTotal($rowTotal)
->setBaseRowTotal($rowTotal);

$subTotal += $rowTotal;
$order->addItem($orderItem);
}

$order->setSubtotal($subTotal)
->setBaseSubtotal($subTotal)
->setGrandTotal($subTotal)
->setBaseGrandTotal($subTotal);

$transaction->addObject($order);
$transaction->addCommitCallback(array($order, 'place'));
$transaction->addCommitCallback(array($order, 'save'));
$transaction->save();

Monday, July 22, 2013

How to remove parent category path from sub category url in Magento

Go to app/code/core/Mage/Catalog/Model/

Open Url.php and go to line no 632 and comment(//) the below line

If you are using Magento 1.5 then please go to line number 797 instead of 632
//if (null === $parentPath) {
//$parentPath = $this->getResource()->getCategoryParentPath($category);
//}
//elseif ($parentPath == '/') {
$parentPath = ''; //('Don't comment it')
//}

Now save and upload it.

Now login to admin panel of your site then go to System->Config->Index Management and click on select all then select Reindex Data from the Action Dropdown then click on submit.

How to Email From A Custom Module In Magento

Magento seemingly makes the most mundane development tasks an exercise in patience. The over engineered PHP beast makes you do more XML situps than the most anal of Java app environments all with zero documentation of its convoluted naming conventions. Therefore, when I wanted to email from within a custom Magento module I found myself back in the Magento source and forums to try and figure it out. I was just about to go down Asad Rahman’s approach or Branko Ajzele’s but digging around in Magento’s source led me to believe there was an easier way. Please note, however, if you want to take a template approach to emailing then you are probably left with the aforementioned approaches and I wish you luck. This approach is very straight forward and about as simple as it gets in Magento. The following function probably doesn’t need a lot of explanation:

public function notify($sendToName, $sendToEmail, $subject, $msg) {

    Mage::log("Sending email to $sendTo");

    $mail = Mage::getModel('core/email');
    $mail->setToName($sendToName);
    $mail->setToEmail($sendToEmail);
    $mail->setBody($msg);
    $mail->setSubject('=?utf-8?B?'.base64_encode($subject).'?=');
    $mail->setFromEmail("support@example.com");
    $mail->setFromName("Your Friendly Neighbourhood Support");
    $mail->setType('text');

    try {
        $mail-->send();
    }
    catch (Exception $e) {
        Mage::logException($e);
        return false;
    }

    return true;
}

Magento Sales Order Grid Customization


 Follow the steps to add column in sales order grid:

Here by i am two column called Payment method and Subtotal.

1 . app/code/local/YourFolderName/AdminHtml

2 . app/code/local/YourFolderName/AdminHtm/Block/Sales/Order/Grid.php

3 . app/code/local/YourFolderName/AdminHtm/etc/config.xml

In Grid.php

class YourFolderName_Adminhtml_Block_Sales_Order_Grid extends Mage_Adminhtml_Block_Sales_Order_Grid
{

public function __construct()
{
Mage_Adminhtml_Block_Widget_Grid::__construct();
$this->setId(‘sales_order_grid’);
$this->setUseAjax(true);
$this->setDefaultSort(‘created_at’);
$this->setDefaultDir(‘DESC’);
$this->setSaveParametersInSession(true);
}
/**
* Retrieve collection class
*
* @return string
*/
protected function _getCollectionClass()
{
return ‘sales/order_grid_collection’;
}

protected function _prepareCollection()
{

$collection = Mage::getResourceModel($this->_getCollectionClass());

//Table Decalration
$salesFlatOrder = (string)Mage::getConfig()->getTablePrefix() . ‘sales_flat_order’;
$salesFlatOrderPayment = (string)Mage::getConfig()->getTablePrefix() . ‘sales_flat_order_payment’;

$collection->getSelect()->join(array(‘sales_flat_order’ => $salesFlatOrder),
“(sales_flat_order.entity_id=main_table.entity_id)”,array(‘base_subtotal’,'sales_flat_order.increment_id as sfo_id’)
);

$collection->getSelect()->join(array(‘sales_flat_order_payment’ => $salesFlatOrderPayment),
“(sales_flat_order_payment.parent_id=main_table.entity_id)”,array(‘method’)
);
echo $collection->printlogquery(‘true’);

$this->setCollection($collection);
return Mage_Adminhtml_Block_Widget_Grid::_prepareCollection();   /* this is must to get your customization collection */

}

protected function _prepareColumns()
{

$this->addColumn(‘increment_id’, array(
‘header’=> Mage::helper(‘sales’)->__(‘Order #’),
‘width’ => ’80px’,
‘type’  => ‘text’,
‘index’ => ‘increment_id’,
‘filter_index’=>’main_table.increment_id’,
));

if (!Mage::app()->isSingleStoreMode()) {
$this->addColumn(‘store_id’, array(
‘header’    => Mage::helper(‘sales’)->__(‘Purchased From (Store)’),
‘index’     => ‘store_id’,
‘type’      => ‘store’,
‘store_view’=> true,
‘display_deleted’ => true,
));
}
$this->addColumn(‘created_at’, array(
‘header’ => Mage::helper(‘sales’)->__(‘Purchased On’),
‘index’ => ‘created_at’,
‘type’ => ‘datetime’,
‘width’ => ’100px’,
));

$this->addColumn(‘billing_name’, array(
‘header’ => Mage::helper(‘sales’)->__(‘Bill to Name’),
‘index’ => ‘billing_name’,
));

$this->addColumn(‘shipping_name’, array(
‘header’ => Mage::helper(‘sales’)->__(‘Ship to Name’),
‘index’ => ‘shipping_name’,
));

$this->addColumn(‘method’, array(
‘header’ => Mage::helper(‘sales’)->__(‘Payment Method’),
‘index’ => ‘method’,
‘filter_index’=>’sales_flat_order_payment.method’,
));

$this->addColumn(‘base_subtotal’, array(
‘header’ => Mage::helper(‘sales’)->__(‘Subtotal’),
‘index’ => ‘base_subtotal’,
‘type’  => ‘currency’,
‘currency’ => ‘base_currency_code’,
‘filter_index’=>’sales_flat_order.base_subtotal’,
));

$this->addColumn(‘base_grand_total’, array(
‘header’ => Mage::helper(‘sales’)->__(‘G.T. (Base)’),
‘index’ => ‘base_grand_total’,
‘type’  => ‘currency’,
‘currency’ => ‘base_currency_code’,
));

$this->addColumn(‘grand_total’, array(
‘header’ => Mage::helper(‘sales’)->__(‘G.T. (Purchased)’),
‘index’ => ‘grand_total’,
‘type’  => ‘currency’,
‘currency’ => ‘order_currency_code’,
));

$this->addColumn(‘status’, array(
‘header’ => Mage::helper(‘sales’)->__(‘Status’),
‘index’ => ‘status’,
‘type’  => ‘options’,
‘width’ => ’70px’,
‘options’ => Mage::getSingleton(‘sales/order_config’)->getStatuses(),
));

if (Mage::getSingleton(‘admin/session’)->isAllowed(‘sales/order/actions/view’)) {
$this->addColumn(‘action’,
array(
‘header’    => Mage::helper(‘sales’)->__(‘Action’),
‘width’     => ’50px’,
‘type’      => ‘action’,
‘getter’     => ‘getId’,
‘actions’   => array(
array(
‘caption’ => Mage::helper(‘sales’)->__(‘View’),
‘url’     => array(‘base’=>’*/sales_order/view’),
‘field’   => ‘order_id’
)
),
‘filter’    => false,
‘sortable’  => false,
‘index’     => ‘stores’,
‘is_system’ => true,
));
}
$this->addRssList(‘rss/order/new’, Mage::helper(‘sales’)->__(‘New Order RSS’));

$this->addExportType(‘*/*/exportCsv’, Mage::helper(‘sales’)->__(‘CSV’));
$this->addExportType(‘*/*/exportExcel’, Mage::helper(‘sales’)->__(‘Excel XML’));

return Mage_Adminhtml_Block_Widget_Grid::_prepareColumns();   /* must */
}

}

In config.xml

<config>
<global>
<blocks>
<adminhtml>
<rewrite>
<sales_order_grid>YourFolderName_Adminhtml_Block_Sales_Order_Grid</sales_order_grid>
</rewrite>
</adminhtml>
</blocks>
</global>
</config>

To follow this steps to get the column in your sales order grid table.

Magento: How to search or filter by multiselect attribute in admin grid


Suppose you have a multi select attribute and you have displayed it in admin grid. You have displayed the multi select attribute options as selection list. Now, you want to filter/search the grid by the multiselect attribute.

The problem here is that the multiselect attribute value is store as comma separated value in database. When we send single value from the selection list, the filter doesn’t work properly.

The solution is to use filter_condition_callback in addColumn.

Here is the code:-
$this->addColumn('categories',
                array(
                    'header'=> Mage::helper('mymodule')->__('Categories'),
                    'index' => 'categories',
                    'width' => '150px',
                    'type' => 'options',
                    'options' => $categories,
                    'filter_condition_callback'
                                => array($this, '_filterCategoriesCondition'),
            ));

The callback function is:-
protected function _filterCategoriesCondition($collection, $column)
{
    if (!$value = $column->getFilter()->getValue()) {
        return;
    }

    $this->getCollection()->addFieldToFilter('categories', array('finset' => $value));
}

The similar thing is done in Mage_Adminhtml_Block_Cms_Block_Grid class to filter Store View.

Hope this helps. Thanks.