Magento – What is the difference between getAllVisibleItems() and getAllItems()?

Before we start with answer of the question, I would like to explain what are these functions. These bothe functionas are used to get all order items,

// load form order ID
$order_id = 1234;
$order = Mage::getModel("sales/order")->load($order_id);
OR
// Get current order ID
$order_id = Mage::getSingleton('checkout/session')->getLastRealOrderId();
$order = Mage::getModel('sales/order')->loadByIncrementId($order_id);
//$order->getSubtotal() ; $order->getGrandTotal() ;
$items = $order->getAllItems(); OR $order->getAllVisibleItems();
$itemcount=count($items);
foreach ($items as $itemId => $item)
{
    $item->getName();
    $item->getPrice();
    $item->getSku();
    $item->getProductId();
    $item->getQtyOrdered(); //$item->getQtyToInvoice();
}

Above code will give all the information of order and ordered items.

Now lets get back to the main question. Let’s look at the code of both methods first,

public function getAllItems()
{
    $items = array();
    foreach ($this->getItemsCollection() as $item) {
       if (!$item->isDeleted()) {
          $items[] = $item;
       }
    }
    return $items;
}
public function getAllVisibleItems()
{
    $items = array();
    foreach ($this->getItemsCollection() as $item) {
       if (!$item->isDeleted() && !$item->getParentItemId()) {
          $items[] = $item;
      }
    }
    return $items;
}

From the code we can see, The only difference is getAllVisibleItems() has an additional check for each item that is,

!$item->getParentItemId()

Which will allow parent item only, It means if you have Configurable Product in your order, getAllVisibleItems will show you only the parent item while getAllItem will show both products.

$order->getAllItems() refers to the all items parent and it’s child (ref: configurable product and it’s child items)
getallitems

$order->getAllVisibleItems() refers to the Parent items only (Ref: configurable product only)
getallvisibleitems

Conclusion, If you need to show order product or do some kind calculation on total ordered items getAllVisibleItems is more preferable.

Magento – Category tree view listing in drop-down

It took bit time to complete this task. After a big fight with the code, finally I am done with the category drop-down with subcategories parent and child tree view.

dropdown post

Here is the code, You can just create bellow function under the block or helper with your module.

function getCategoriesTreeView() {
    // Get category collection
    $categories = Mage::getModel('catalog/category')
        ->getCollection()
        ->addAttributeToSelect('name')
        ->addAttributeToSort('path', 'asc')
        ->addFieldToFilter('is_active', array('eq'=>'1'))
        ->load()
        ->toArray();

    // Arrange categories in required array
    $categoryList = array();
    foreach ($categories as $catId => $category) {
        if (isset($category['name'])) {
            $categoryList[] = array(
                'label' => $category['name'],
                'level'  =>$category['level'],
                'value' => $catId
            );
        }
    }
    return $categoryList;
}

Now its time for design, bellow is the code which will give you the category drop down.

<select id="categorylist" name="categorylist">
<option value="">Select Category</option>
<?php
    $categoriesTreeView = getCategoriesTreeView();

    foreach($categoriesTreeView as $value)
    {
        $catName    = $value['label'];
        $catId      = $value['value'];
        $catLevel    = $value['level'];

        $space = '&nbsp;';
        for($i=1; $i<$catLevel; $i++){
            $space = $space."&nbsp;";
        }
        $catName = $space.$catName;

?>
     <option value="<?php echo $catIdIs; ?>"><?php echo $catName ?></option>
 <?php
    }
?>
</select>

With the same code you can create category switcher / category changer. Just you need to get the category’s URL with the category collection and redirect to that category with on change event of drop-down.

Magento – Blank white screen frontend issue

Magento shows blank/empty page, I was scared when this happened on one of the live site but after some exercises with source code and using internet I come to find out the solution. Most probably it could have memory issue or the compilation tool.

In order to troubleshoot the issue,  your first step is to edit index.php, find out bellow line and uncomment

ini_set('display_errors', 1);

If its not available, insert this line somewhere at the top of the file and try out bellow solutions.

Try – 1 : Disable Complier

Go to System -> Tools -> Compilation and Disable you Complier and clear/flush magento cache data. In most of the cases this would solve the issue.

Try – 2 : Improve PHP Memory Limit

If you can access php.ini OR using .htaccess in the root OR edit index.php add bellow line right after ini_set(‘display_errors’, 1);

ini_set('memory_limit', '256M');

Try – 3 : Design changes

If you have recently installed new theme try to switch interface to a previously used one. Flush Magento cache after each operation. Magento will switch to default theme if it can not find a custom one.

I hope these would resolve  your problem.

Magento – Show Product Reviews on Product detail Page

Product review is one of the good feature of magento but with default magento theme product review listed on separate page. Usually  customer like to see all detail on same page instead redirect to another page. With this though we would like to show the product reviews  on product detail page only.

Bellow are steps which can help you to show product reviews on product detail page.

Step-1
Call product review block on product detail page, you can add bellow code to local.xml

<catalog_product_view>
    <reference name="content">
        <block type="review/product_view_list" name="product.info.product_additional_data" as="reviews" template="review/product/view/review_summary.phtml" />
    </reference name="content">
</catalog_product_view>

step-2
Create new template file review_summary.phtml, under template/review/product/view/ folder

<?php 
    $_items = $this->getReviewsCollection()->getItems();
    if( count( $_items ) )
    {
        foreach( $_items as $_review ){
        // Get the Review Title
        echo $this->htmlEscape( $_review->getTitle() );
        // Get the Review Content
        echo $this->htmlEscape( $_review->getDetail() );
        // Get the Review Author
        echo $this->htmlEscape( $_review->getNickname() );
        } 
    } 
?>

Step-3
Call review block on view.phtml, where you need the block to be show based on your design.

<?php echo $this->getChildHtml('reviews') ?>

Magento – Get current module name, route name, controller name and action name

Many time we required to get current controller or action name or module name. Its very easy job to get get route name, module name, controller and action name for magento from current URL, anywhere in controller or even with template files.

Mage::app()->getRequest()->getControllerName(); // return controller name

Mage::app()->getRequest()->getActionName(); // return action name

Mage::app()->getRequest()->getRouteName(); // return routes name

Mage::app()->getRequest()->getModuleName(); // return module name

Magento – Insert Static Block in Magento Templates

There are basically three ways to insert static blocks into magento templates

1.Inserting into template-file.phtml

<?php
     echo  $this->getLayout()->createBlock('cms/block')->setBlockId('CMS-block-id')->toHtml() ;
?>

2. Inserting into CMS

{{block type="cms/block" block_id="CMS-block-id" template="cms/example-template.phtml"}}

3. Inserting into layout.xml

<layout>
    <example>
    <reference name="content">
     <block type="cms/block" name="cms_store_check">
     <action method="setBlockId"><block_id>CMS-block-id</block_id></action>
     </block>
     </reference>
     </example>
</layout>

Magento remove index.php from URL

Normally we find index.php in URL, and mostly we don’t like it to be there. This post will allow you to change your URL from

http://www.yourdomain.com/index.php/about

to

http://www.yourdomain.com/about

For that,

go to Admin > System > Configuration > Web > Search Engine Optimization,
change the value of Web Server Rewrites to Yes.

Make sure, your web server rewrite module is enabled and Check the file permission of .htaccess, it should be present in Magento root directory and readable by server.

Magento – get directory paths, get Base URLs, get URLs in static block, get secure URL

This post help you to get url, directory path, to get module URL. This is very basic post, that will help to beginners.

Get Base URL

 Mage::getBaseUrl() => Get base url path e.g. http://yourwebsite.com/
 Mage::getBaseUrl('media') => Get MEDIA folder path e.g. http://yourwebsite.com/media/
 Mage::getBaseUrl('js') => Get JS folder path e.g. http://yourwebsite.com/js/
 Mage::getBaseUrl('skin') => Get SKIN folder path e.g. http://yourwebsite.com/skin/

Get Current URL

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

Get Home URL

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

Create module your

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

Get secure URL
To get secure URL you just need to add one more parameter as bellow,

Mage::getUrl('',array('_secure'=>true))
Mage::getUrl('module/controller/action',array('_secure'=>true))

Get Directory paths

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

Same way you can get more directory path,
Mage::getBaseDir(‘design’) => Get design directory path
Mage::getBaseDir(‘code’) => Gives code directory file path
Mage::getBaseDir(‘lib’) => Gives lib directory file path
Mage::getBaseDir(‘skin’) => Gives skin directory file path
Mage::getBaseDir(‘var’) => Gives var directory file path
Mage::getBaseDir(‘cache’) => Gives cache directory file path
Mage::getBaseDir(‘log’) => Gives log directory file path

Get URL path in Static Block
Get Base URL

{{base url=''}}

Get Skin URL

{{skin url='images/skinimage.jpg'}}

Get Media URL

{{media url='/mediaimage.jpg'}}

Get Store URL

{{store url=''}}

Magento – Pass variables to block

With this post I will described various ways to pass variables to block.

1. Run time in PHTML file

$productId = 10;
$this->getChild('testblock')->setData("productId", $productId);
echo $this->getChildHtml('testpage', fales);

NOTE: second parameter ‘false’ is to tell, not to cache block.

2. Pass variables from a layout to a block
Yes, We can insert variable into a block from layout xml file as bellow,

<reference name="root">
   <block type="yourmodule/testblock" name="testpage">
        <action method="setData"><name>product_id</name><value>10</value></action>
   </block>
</reference>

Using the action tag with the method=”setData” attribute. Its child tags name and value to set variable and its value.
setData method of block is called when the system loads layout. name, value tags are parameters of setData method.

In block file you can access this by,

$productId = $this->getProductId(); 
or
$productId = $this->getData(‘product_id’);

3. Used in CMS page
we can put variables into a block by,

{{block type="yourmodule/testblock" product_id=10 template="module/yourmodule/bestproduct.phtml"}}

Set different themes for logged in users – Magento

Some time we need to setup the different theme for logged in users, here is the code

<?php
     if(Mage::getSingleton('customer/session')->isLoggedIn()){
	 Mage::getDesign()->setPackageName('package_name')->setTheme('themename');
     }
?>