Pages

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 = '';
}