Friday, March 23, 2012

A list of some useful code snippets for Magento developers


1. Check if customer is logged in:
if(!Mage::getSingleton('customer/session')->isLoggedIn())
{
 $this->_redirect('customer/account/login/');
}
2. Get current site url:
Mage::getUrl();
3. Get Category URL:
$categoryUrl = Mage::getModel('catalog/category')->load($categoryId)->getUrl();
4. Get product URL:
$productId = 1;
$product = Mage::getModel('catalog/product')->load($productId);
$path = Mage::getUrl().$product->getUrlPath();
5. Get Product image path:
$productId = 1;
$product = Mage::getModel('catalog/product')->load($productId);
$path = Mage::helper('catalog/image')->init($product, 'image')->resize(75, 75);
6. Format a number as price:
$this->formatPrice(10);
7. Call a .phtml explicitly:
echo $this->getLayout()->createBlock('sales/order_recent')->setTemplate('sales/order/recent.phtml')->toHtml();
8. Get Currency Code:
Mage::app()->getStore()->getCurrentCurrencyCode();
9. Get Currency Symbol:
Mage::app()->getLocale()->currency(Mage::app()->getStore()->getCurrentCurrencyCode())->getSymbol();
10. Get Customer Shipping/Billing Address:
$customerAddressId = Mage::getSingleton('customer/session')->getCustomer()->getDefaultShipping();
if ($customerAddressId){
       $address = Mage::getModel('customer/address')->load($customerAddressId);
}
11. Get all products in the cart:
$mageFilename = 'app/Mage.php';
require_once $mageFilename;
umask(0);
Mage::app();

// Secret Sauce - Initializes the Session for the FRONTEND
// Magento uses different sessions for 'frontend' and 'adminhtml'
Mage::getSingleton('core/session', array('name'=>'frontend'));

$session = Mage::getSingleton('checkout/session');
foreach ($session->getQuote()->getAllItems() as $item)
{
 $productid      = $item->getProductId();
 $name       = $item->getName();
 $qty       = $item->getQty();

 echo "Product Id-".$productid.', Name-'.$name. ', Quantity-'.$qty;
}
12. Find which class is loaded in current template:
<?php
    print_r(get_class_methods(get_class($this)));
?>
or
<?php
    print_r($this->debug());
?>
or
<?php
    echo Zend_Debug::dump($this);
?>
13. Get Current theme folder:
<?php echo $this->getSkinUrl('') ?>
14. Get total price of items in the cart:
<?php echo $this->helper('checkout')->formatPrice(Mage::getSingleton('checkout/cart')->getQuote()->getGrandTotal()); ?>
15. Get the current category:
<?php
    $currentCategory = Mage::registry('current_category');
?>
16. Add product to cart through querystring:
http://www.mydomain.com/checkout/cart/add?product=[id]&qty=[qty]
http://www.mydomain.com/checkout/cart/add?product=[id]&qty=[qty]&options[id]=[val

1 comment:

  1. Dear Bhoopendra,

    I am a beginner in Magento.

    Though I am yet to test the above code, it appears to be an excellent work.

    Keep it up!

    Colonel SC Sood (Retd), Professor
    satishsood1@gmail.com
    Mobile: 9216508708

    ReplyDelete