Most common & frequently used Functions in Magento development

Mohan Dave · · 3292 Views
Most common & frequently used Functions in Magento development

Magento is a very highly effective and thus a little bit challenging to theme CMS. It is designed on the Zend framework, and it often becomes a challenging task to develop or modify Magento templates. Here in this post, I’ll try to cover a brief list of useful Magento template development functions, which are used regularly during theme development.

1. Magento Check & Get Secure URL

1.1. Check if Secure URL is enabled in Frontend

if (Mage::app()->getStore()->isFrontUrlSecure()) {
       echo 'Secure URL is enabled in Frontend';
}

1.2. Magento Check if Secure URL is enabled in Admin

if (Mage::app()->getStore()->isAdminUrlSecure()) {
      echo 'Secure URL is enabled in Admin';
}

1.3. Magento Check if current URL is Secure

if (Mage::app()->getStore()->isCurrentlySecure()) {
     echo 'Current URL is Secure';
}

1.4. Magento Check if current page is Frontend or Admin

if (Mage::app()->getStore()->isAdmin()) {
    echo 'You are in Admin page';
} else {
    echo 'You are in Frontend page';
}

1.5. Magento Get Base Url

echo Mage::getBaseUrl($type = 'link', $secure = true);

1.6. Magento Get Shopping Cart URL:

echo Mage::getUrl('checkout/cart', array('_secure'=>true));

2. Magento How to check if current page is homepage?

2.1. If you are in template/page/html/header.phtml

if($this->getIsHomePage()) {
     echo 'You are in Homepage!';
}

2.2. In any other .phtml template file or in any other .php class file

if(Mage::getBlockSingleton('page/html_header')->getIsHomePage()) {
     echo 'You are in Homepage!';
}

2.3. Alternative way

$routeName = Mage::app()->getRequest()->getRouteName();
$identifier = Mage::getSingleton('cms/page')->getIdentifier();
 
if($routeName == 'cms' && $identifier == 'home') {
   echo 'You are in Homepage!';
}

3. Get current URL of the page

3.1. From Mage_Core_Helper_Url class

$currentUrl = Mage::helper('core/url')->getCurrentUrl();

3.2. From Mage_Core_Model_Store class

$currentUrl = Mage::app()->getStore()->getCurrentUrl(false);

3.3. If some missing css, js, images etc

if (!in_array(Mage::app()->getFrontController()->getAction()->getFullActionName(), array('cms_index_noRoute', 'cms_index_defaultNoRoute'))) {
     $currentUrl = Mage::helper('core/url')->getCurrentUrl();
}

3.4. Base URL

3.4.1. Get base url path

Mage::getBaseUrl() //e.g. http://yourwebsite.com/

3.4.2. Get home URL

Mage::helper('core/url')->getHomeUrl();

3.4.3. Get MEDIA folder path

Mage::getBaseUrl('media')   //e.g. http://yourwebsite.com/media/

3.4.4. Get JS folder path

Mage::getBaseUrl('js')  //e.g. http://yourwebsite.com/js/

3.4.5. Get SKIN folder path

Mage::getBaseUrl('skin')  //e.g. http://yourwebsite.com/skin/

3.4.6. Get url of custom module

Mage::getUrl('module/controller/action');

3.4.7. CMS Page

Mage::getUrl('*/*');// http://www.example.com/cms/page/

3.4.8. Custom Page URL

Mage::getUrl('index.html'); // http://www.example.com/index.html

3.4.9. CMS Page with id

Mage::getUrl('cms/page/view', array('id' => 1)); // http://www.example.com/cms/page/view/id/1

4. Customer

4.1. Get Customer Login URL

Mage::getUrl(‘customer/account/login’);

4.2. Get Customer LogOut URL

Mage::getUrl(‘customer/account/logout’);

4.3. Get Customer My Account URL

Mage::getUrl(‘customer/account’);

4.4. Get User Register URL

Mage::getUrl(‘customer/account/create’);

4.5. Get Customer Checkout URL

Mage::getUrl(‘checkout/cart’);

4.6. Check Customer Logged in

helper('customer')->isLoggedIn()

4.7. Check whether the customer is logged in the magento system or not.

$session=Mage::getSingleton('customer/session', array('name'=>'frontend') );
 
if ($session->isLoggedIn()) {
     echo "Welcome, ".$session->getCustomer()->getName();
} else {
     echo "Not logged in";
}

4.8. Get customer id.

echo $customerId = Mage::getModel('customer/session')->getCustomerId();

4.9. Get guest id.

echo $vistitorId = Mage::getModel('core/session')->getVisitorId();

4.10. Check whether admin is logged in or not in a magento site.

$adminsession = Mage::getSingleton('admin/session', array('name'=>'adminhtml'));
 
if($adminsession->isLoggedIn()) {
     echo "Welcome Admin";
} else {
     echo "Not logged in";
}

5. Get Current Directory Paths

5.1. Get Base Directory

Mage::getBaseDir()
//output : /var/www/html/magento

5.2. Get Magento app Directory

Mage::getBaseDir('app')
//output : /var/www/html/magento/app

5.3. Get Media Directory

Mage::getBaseDir('media')
//output : /var/www/html/magento/media

5.4. Get design directory path

Mage::getBaseDir('design')

5.5. Get code directory file path

Mage::getBaseDir('code')

5.6. Get lib directory file path

Mage::getBaseDir(‘lib’)

5.7. Get skin directory file path

Mage::getBaseDir(‘skin’)

5.8. Get var directory file path

Mage::getBaseDir(‘var’)

5.9. Get cache directory file path

Mage::getBaseDir(‘cache’)

5.10. Get log directory file path

Mage::getBaseDir(‘log’)

5.11. Get URL Path in Static Block

Get Base URL
{{base url=''}} =>
{{base url='magento-page.html'}} => Get specified page url
 
Get Skin URL
{{skin url='images/skinimage.jpg'}} =>
 
Get Media URL
{{media url='/mediaimage.jpg'}} =>
 
Get Store URL
{{store url=''}} =>

6. Get currency code & currency rate

6.1. Get Base Currency Code

Mage::app()->getStore()->getBaseCurrencyCode();

6.2. Get Default Currency Code

Mage::app()->getStore()->getDefaultCurrencyCode();

6.3. Get Current Currency Code

Mage::app()->getStore()->getCurrentCurrencyCode();
Get Available/Allowed Currency Codes
$availableCurrencyCodes = Mage::app()->getStore()->getAvailableCurrencyCodes();
 
//OR
 
$currencyModel = Mage::getModel(‘directory/currency’);
$currencies = $currencyModel->getConfigAllowCurrencies();

6.4. Get Current Currency Rate

Mage::app()->getStore()->getCurrentCurrencyRate();

6.5. Get currency rates of allowed currencies

Mage::getModel('directory/currency')->getCurrencyRates($baseCurrencyCode, array_values($allowedCurrencies));

6.7. Changing price from any one currency to another

Mage::helper('directory')->currencyConvert($price, $from, $to);

6.8. Convert price from current currency to base currency

Mage::helper('directory')->currencyConvert($price, $currentCurrencyCode, $baseCurrencyCode);

6.9. Get currency rates for Nepalese Currency

$allowedCurrencies = Mage::getModel('directory/currency')->getConfigAllowCurrencies();
Mage::getModel('directory/currency')->getCurrencyRates('NPR', array_values($allowedCurrencies));

6.10. Get currency symbol by currency code

Mage::app()->getLocale()->currency($currency_code )->getSymbol();
Mage::app()->getLocale()->currency(Mage::app()->getStore()->getCurrentCurrencyCode())->getSymbol();

7. Modules

7.1. To Check module enabled

helper('core')->isModuleOutputEnabled($moduleName)

7.2. To get list of all modules

Mage::getConfig()->getNode('modules')->children();

7.3. Check whether any particular module is active

$modules = Mage::getConfig()->getNode('modules')->children();
$modulesArray = (array)$modules;
 
if($modulesArray['Mage_Paypal']->is('active')) {
     echo "Paypal module is active.";
} else {
     echo "Paypal module is not active.";
}

8. General Store-Related Functions

8.1. Display products list page (list.phtml).

echo $this->getProductListHtml();

8.2. Get current store id.

echo $storeId = Mage::app()->getStore()->getId();

8.3. Get current store name.

echo $storeName = Mage::app()->getStore()->getName();

8.4. Get current store code.

echo $storeCode = Mage::app()->getStore()->getCode();

8.5. Get website name.

echo $websiteName = Mage::app()->getWebsite()->getName();

8.6. Get session id.

echo $sessionId = Mage::getModel('core/session')->getSessionId();

9. Product/Category-Related Functions

9.1. Get list of all Categories

$categories = Mage::getModel('catalog/category')
->getCollection()
->addAttributeToSelect('*');

9.2. Get all active categories

$categories = Mage::getModel('catalog/category')
->getCollection()
->addAttributeToSelect('*')
->addIsActiveFilter();

9.3. Get the product link.

echo $this->getProductData()->getProductUrl();

9.4. Get the product name.

echo $this->htmlEscape($this->getProductData()->getName());

9.5. Get Image url of current category.

echo $this->getCurrentCategory()->getImageUrl();

9.6. Check whether the current category is Top category.

echo $this->IsTopCategory();

9.7. Get description of current category.

echo $this->getCurrentCategory()->getDescription();

9.8. Load the current category (from category page).

$_category = Mage::getModel('catalog/layer')->getCurrentCategory();

9.10. Get Current Category:

$_current_category = Mage::registry('current_category');

9.11. Load category by category id:

$_category = Mage::getModel('catalog/category')->load($category_id);

9.12. Load Product by product id:

$_product = Mage::getModel('catalog/product')->load($product_id);

9.13. Load Product by SKU:

$_product = Mage::getModel('catalog/product')->loadByAttribute('sku', $product_sku);

9.14. Get product images with customized parameters (size, style, etc.) from product/view/media.phtml file

$this->helper('catalog/image')->init($_product, $_image_attribute_name)->keepFrame(false) // if true, will ensure that image has dimensions in $width/$height
->constrainOnly(true) // if true, will ensure that image's height or width do not exceed its actual width or height
->keepAspectRatio(true) // if true, will guarantee that image's height, width ratio remain intact
->resize($_image_width, $_image_height); // parameters given there are used for as lengths for width and height.

10. Cart/Checkout-Related Functions

10.1. Get all products in cart

$session= Mage::getSingleton('checkout/session');
$items = $session->getQuote()->getAllItems();

10.2. Get total items and total quantity in cart

$totalItems = Mage::getModel('checkout/cart')->getQuote()->getItemsCount();
$totalQuantity = Mage::getModel('checkout/cart')->getQuote()->getItemsQty();

10.3. Get subtotal and grand total price of cart

$subTotal = Mage::getModel('checkout/cart')->getQuote()->getSubtotal();
$grandTotal = Mage::getModel('checkout/cart')->getQuote()->getGrandTotal();

10.4. Get products details present in your cart

$items = Mage::getSingleton('checkout/session')->getQuote()->getAllItems();
foreach($items as $item) {
    echo 'ID: '.$item->getProductId().'<br />';
    echo 'Name: '.$item->getName().'<br />';
    echo 'Sku: '.$item->getSku().'<br />';
    echo 'Quantity: '.$item->getQty().'<br />';
    echo 'Price: '.$item->getPrice().'<br />';
}

11. CMS Page-Related Functions

{=store url=""=} //same as Mage::getBaseUrl();
{=skin url='images/imagename.jpg'=} //same as $this->getSkinUrl('images/imagename.jpg');
to access a specific page
{=store url='mypage.html'=} //same as $this->getUrl('mypage.html');
{=media url='/imagename.jpg'=}

11.1. Call a Magento static block from within a CMS page content area

{{block type="cms/block" block_id="your_block_identifier" template="cms/content.phtml"}}

11.2. Add Bread Crumb

$this->getLayout()->getBlock('breadcrumbs')->toHtml();

11.3. Call static block from template file

echo $this->getLayout() ->createBlock('cms/block') ->setBlockId('block_identifier') ->toHTML();

11.4. Call a static block in .phtml file.

echo $this->getLayout()->createBlock('cms/block')->setBlockId('YOURBLOCKID')->toHtml();

11.5. Display CMS block page.

echo $this->getCmsBlockHtml();

12. Product Collections Related Functions

Product Collection class in magento is Mage_Catalog_Model_Resource_Eav_Mysql4_Product_Collection

12.1. Get All Products of a category

$collection = Mage::getResourceModel('catalog/product_collection')
->setStoreId($this->getStoreId())
->addCategoryFilter($category);

12.2. Get All products which are visible in front end.

$collection = Mage::getResourceModel('catalog/product_collection');
Mage::getSingleton('catalog/product_visibility')->addVisibleInCatalogFilterToCollection($collection);

12.3. Get all products which are enabled

$collection = Mage::getResourceModel('catalog/product_collection');
Mage::getSingleton('catalog/product_status')->addVisibleFilterToCollection($collection);

12.4. Add Product Price To Collection

$collection = Mage::getResourceModel('catalog/product_collection');
$collection ->addMinimalPrice()
->addFinalPrice()
->addTaxPercents();

12.5. Filter collections by product ids.

$collection = Mage::getResourceModel('catalog/product_collection');
$collection->addIdFilter(array(1,2,3));
//$collection->addIdFilter(array(1,2,3),false);

In above code snippet only product with ids 1,2,3 remain in the collection. The function parameter is true/false, this means include or exclude products from collection.

12.6. Add Website ID to the collection

$collection = Mage::getResourceModel('catalog/product_collection');
$collection->addWebsiteNamesToResult();

This code snippet adds website_id of each product to that collection. Only useful when using multiple websites in magento.

12.7. Filter Current Store Products

$collection = Mage::getResourceModel('catalog/product_collection');
$collection->addStoreFilter();

12.7. Filter Current Website Products

$collection = Mage::getResourceModel('catalog/product_collection');
$collection->addWebsiteFilter();

12.8. Get All Products Ids

$collection = Mage::getResourceModel('catalog/product_collection');
$collection->getAllIds();

This returns an array with only products ids of collection.

12.9. Add SEO Product URL

$collection = Mage::getResourceModel('catalog/product_collection');
$collection->addUrlRewrite();

This adds SEO friends urls to our product collection.

12.10. Add Category Ids

$collection = Mage::getResourceModel('catalog/product_collection');
$collection->addCategoryIds();

This will add category ids to the products.

12.11. Add Tier Pricing

$collection = Mage::getResourceModel('catalog/product_collection');
$collection->addTierPriceData();

12.12. Magento Filtering Collections

addAttributeToFilter() is used to filter EAV collections. addAttributeToFilter() will filter the products in accordance with the attributes that you’ve included in your collection.

addFieldToFilter() is used to filter Non-EAV collections. addFieldToFilter() will filter the items based on columns in the database from the table catalog_product_entity.

addFieldToFilter() is mapped to addAttributeToFilter() for EAV entities. So you can just use addFieldToFiler().

// app/code/core/Mage/Eav/Model/Entity/Collection/Abstract.php
public function addFieldToFilter($attribute, $condition = null) {
   return $this->addAttributeToFilter($attribute, $condition);
}

12.13. Select collection by product attribute

$collection = Mage::getModel(‘catalog/product’)->getCollection();
//fetch name and orig_price into data
$collection->addAttributeToSelect('name');
$collection->addAttributeToSelect('orig_price');
 
//filter for products who name is equal (eq) to 100, or equal (eq) to 200
$collection->addFieldToFilter(array(
  array('name'=>'orig_price','eq'=>'100'),
  array('name'=>'orig_price','eq'=>'200'),
));

addAttributeToFilter() is the function that can be called on a product collection in Magento. In other words, it adds a condition to the WHERE section of the MySQL query used to extract a product collection from the database.

$collections = Mage::getModel('catalog/product')
->getCollection()
->addAttributeToSelect(array('name', 'price'))
->addAttributeToFilter('price', array('eq' => 10.00))
->load();

12.14. Debugging The SQL Query

There are two ways to debug the query being executed when loading a collection in Magento.

// Method 1 prints the query out as well as loading the products
Mage::getModel('catalog/product')->getCollection()->load(true);
 
// Method 2 will just convert the query object to a string (ie. will print out the SQL).
$collection = Mage::getModel('catalog/product')->getCollection();
 
echo $collection->getSelect();

12.15. AND & OR Operation

When you do query in database, we often need to make either OR or AND operation or even both. How do we create this in Magento?

$collections = Mage::getModel('catalog/product')
			->getCollection()
			->addAttributeToSelect(array('name', 'price'))
			->addAttributeToFilter('name', array('eq' => 'magento'))
			->addAttributeToFilter('price', array('eq' => 100.00))
			->load();
 
//OR
 
$collections = Mage::getModel('catalog/product')
			->getCollection()
			->addAttributeToSelect(array('name', 'price'))
			->addAttributeToFilter(
				array(
					'attribute' => 'name',
					'eq' => 'mangeto',
				),
				array(
					'attribute' => 'price',
					'eq' => 100.00,
				),
			)->load();

12.16. Use of operators with examples:

// Equals: eq
$_products->addAttributeToFilter('status', array('eq' => 1));

// Not Equals – neq
$_products->addAttributeToFilter('sku', array('neq' => 'spiderman'));


// Contains – Like – like
$_products->addAttributeToFilter('sku', array('like' => '%spiderman%'));


// Not contains – not Like – nlike
$_products->addAttributeToFilter('sku', array('nlike' => '%spiderman%'));


// Contains – In – in
$_products->addAttributeToFilter('id', array('in' => array(15,25,35,40,41,42,43)));


// No Contain – Not In – nin
$_products->addAttributeToFilter('id', array('nin' => array(15,25,35,40,41,42,43)));


// Null- null
$_products->addAttributeToFilter('description', 'null');


// not Null- null
$_products->addAttributeToFilter('description', 'notnull');


// Greater than – gt
$_products->addAttributeToFilter('price', array('gt' => 5));


// Less than – lt
$_products->addAttributeToFilter('price', array('lt' => 25));


// Greater than o equals to – gteq
$_products->addAttributeToFilter('price', array('gteq' => 5));


// Less than o equals to – lteq
$_products->addAttributeToFilter('price', array('lteq' => 25));
//If we want to use it in other classes, try withAddFieldToFilter() function, whose uses in the same way.


// Filtering by date:
$productCollection = Mage::getModel('catalog/product')->getCollection()
	->addAttributeToFilter('updated_at', array(
		'from' => '2014-02-14',
		'to' => '2015-12-25',
	))->load();
0

Please login or create new account to add your comment.

0 comments
You may also like:

Getting the admin panel URLs in Magento

A page in Magento’s administration panel works similar to front-end pages, there is an admin controller for each of all pages in the admin panel. The controller resides in the (...)
Mohan Dave

How to format price in Magento?

There are a couple of methods to format price in Magento. The easiest and most used is:
Mohan Dave