Pages

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;