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.

Advertisements

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 – Onepage checkout not working after upgrade/update Magento 1.8

We have resolve the issue with top menu navigation after upgrade magento to least version. Just recently I get new issue with checkout page that, step 3 Shipping Method is not working after upgrade magento 1.8 with my custom theme. Checkout process is stuck on step 3 Shipping Method.

After exploring web and debugging the code I have found solution. In order to resolve this issue you just need to add new class to html tag fieldset as shown below,

Go to /app/design/frontend/base/default/template/checkout/onepage/payment.phtml

look for the code

<fieldset>
<?php echo $this->getChildHtml('methods') ?>
</fieldset>

change it to this

<fieldset id="checkout-payment-method-load">
<?php echo $this->getChildHtml('methods') ?>
</fieldset>

I hope this would resolve your issue….

Topmenu not functioning after upgrade magento 1.8 fatal error addCacheTag()

As we seen with my previous blog upgrade community edition magento 1.7 to magento 1.8,  we know how to upgrade magento with latest version.

When I was doing the same with one my project, I come across the error something like,

Fatal error: Call to a member function addCacheTag() on a non-object in (Base Path)/app/code/core/Mage/Catalog/Model/Observer.php on line 215

For quick fix, initially I have comment out two lines from file app/code/core/Mage/Catalog/Model/Observer.php

Line # 241 ($menuBlock->addModelTags($categoryModel);) 
Line # 215 ($block->addCacheTag(Mage_Catalog_Model_Category::CACHE_TAG);)

But after spending some time, I come to know that I have used one of the menu extension which is exptending the “Mage_Page_Block_Html_Topmenu” and there is some problem with Mage::dispatchEvent.

With my extended code it was just something like

Mage::dispatchEvent('page_block_html_topmenu_gethtml_before', array(
          'menu' => $this->_menu
));

Updated code is,

Mage::dispatchEvent('page_block_html_topmenu_gethtml_before', array(
        'menu' => $this->_menu,
        'block' => $this         //add this line
));

Most probebly this would resolve your issue.

How to upgrade magento to 1.8

Magento 1.8 has been released with,

  • Major overhaul of tax calculation formulas, correction of rounding errors, and additional assistance with configuration.
  • Optimized cache adapters for single-server systems.
  • Upgraded Redis cache adapters for multi-server systems.
  • Eliminated many types of database deadlocks.
  • And many more updates and changes………..

Now, Magento developers get a new JOB to upgrade magento from older version to magento 1.8.

Magento recommends you upgrade your installation using the following guidelines in a development or test environment, separate from your existing production environment:

  1. Create a parallel development or testing system, identical to your current production system.
    • You’ll use this parallel system to implement and test the Magento upgrade.
  2. In your current production environment:
    • Back up your Magento database.
    • Archive the file system. This includes the media directory and subdirectories; all extensions and customizations; and all custom themes.
  3. In the development or test environment:
    • Create a new, empty database instance.
    • Import the production database tables into the development database instance.
    • Copy your production media directory, extensions, themes, and other customizations to the development system.
    • Copy local.xml to magento-install-dir/app/etc and edit it if necessary to reference the production database instance.
    • In a web browser, go to your development system base URL.
    • Wait for upgrade scripts to run.
    • Verify the development system is now identical to the production system.
    • If not, fix issues, retest, and upgrade again.
  4. Test the development system thoroughly, including:
    • Verify all extensions, themes, and customizations work.
    • Place orders using all webstores and all payment methods.

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 query master

This post is collection of mysql query to perform particular task, this will make you life easy.

NOTE : Basically this is not good practis to work with database directlly for live project. Make sure that you have database back up before run query.

Update customer group of all subscriber customer using query – Magento

UPDATE
    customer_entity,
    newsletter_subscriber
SET
    customer_entity.`group_id` = 5
WHERE
    customer_entity.`entity_id` = newsletter_subscriber.`customer_id`
AND
    newsletter_subscriber.`subscriber_status` = 1;

Turn template hints on/off using query – Magento

UPDATE
   core_config_data
SET
   value = 0
WHERE
   path = "dev/debug/template_hints"
OR
   path = "dev/debug/template_hints_blocks";

Change admin user password using query – magento

UPDATE admin_user SET password=CONCAT(MD5('qXpassword'), ':qX') WHERE username='admin';

Delete particular order using query – Magento

SET @increment_id='43290';
SELECT @order_id:=entity_id FROM sales_order_entity WHERE increment_id=@increment_id;
DELETE FROM sales_order_entity WHERE entity_id=@order_id OR parent_id=@order_id;
DELETE FROM sales_order WHERE increment_id=@increment_id;

Mass Exclude/Unexclude Images using query – Magento

//Mass Unexclude
UPDATE`catalog_product_entity_media_gallery_value` SET `disabled` = '0' WHERE `disabled` = '1';
//Mass Exclude
UPDATE`catalog_product_entity_media_gallery_value` SET `disabled` = '1' WHERE `disabled` = '0';

Delete all products using query – Magento

TRUNCATE TABLE `catalog_product_bundle_option`;
TRUNCATE TABLE `catalog_product_bundle_option_value`;
TRUNCATE TABLE `catalog_product_bundle_selection`;
TRUNCATE TABLE `catalog_product_entity_datetime`;
TRUNCATE TABLE `catalog_product_entity_decimal`;
TRUNCATE TABLE `catalog_product_entity_gallery`;
TRUNCATE TABLE `catalog_product_entity_int`;
TRUNCATE TABLE `catalog_product_entity_media_gallery`;
TRUNCATE TABLE `catalog_product_entity_media_gallery_value`;
TRUNCATE TABLE `catalog_product_entity_text`;
TRUNCATE TABLE `catalog_product_entity_tier_price`;
TRUNCATE TABLE `catalog_product_entity_varchar`;
TRUNCATE TABLE `catalog_product_link`;
TRUNCATE TABLE `catalog_product_link_attribute_decimal`;
TRUNCATE TABLE `catalog_product_link_attribute_int`;
TRUNCATE TABLE `catalog_product_link_attribute_varchar`;
TRUNCATE TABLE `catalog_product_option`;
TRUNCATE TABLE `catalog_product_option_price`;
TRUNCATE TABLE `catalog_product_option_title`;
TRUNCATE TABLE `catalog_product_option_type_price`;
TRUNCATE TABLE `catalog_product_option_type_title`;
TRUNCATE TABLE `catalog_product_option_type_value`;
TRUNCATE TABLE `catalog_product_super_attribute`;
TRUNCATE TABLE `catalog_product_super_attribute_label`;
TRUNCATE TABLE `catalog_product_super_attribute_pricing`;
TRUNCATE TABLE `catalog_product_super_link`;
TRUNCATE TABLE `catalog_product_enabled_index`;
TRUNCATE TABLE `catalog_product_website`;
TRUNCATE TABLE `catalog_product_entity`;
TRUNCATE TABLE `cataloginventory_stock_item`;
TRUNCATE TABLE `cataloginventory_stock_status`;

Magento – Filter product collection by multiple categories

Magento providing verious type of filter that can be used directly from product collection. Including category filter,

$_category = Mage::getModel('catalog/category')->load($category_id);
$collection= Mage::getResourceModel('catalog/product')->getCollection()->addCategoryFilter($_category);

But the issue is with multiple categories to filter. You can use bellow code to overcome this problem,

$collection = Mage::getModel('catalog/product')->getCollection()
             ->addAttributeToSelect('*')
             ->addFieldToFilter('is_saleable',1)
             ->joinField('category_id', 'catalog/category_product', 'category_id', 'product_id = entity_id', null, 'left')
             ->addAttributeToFilter('category_id', array(
                 array('finset' => '4'),
                 array('finset' => '8'))
               )
             ->addAttributeToSort('created_at', 'desc');

How magento store password and validate password – Magento

Magento uses MD5 and salt algorithems to store password for customer as well admin user.

How magento create encrypted password

Magento create encrypted password with,

Mage::getModel('core/encryption')->decrypt($password);

Here is the logic of decrypt($password) function,

 $password = "12345678";
 $salt = "at";
 $encyPasswod = md5($salt.$pass).":".$salt;

In above function, $salt is randomly generated string of two alphanumeric character.

How magento validate password

Bellow functiona will validate the user password,

Mage::getModel('customer/customer')->authenticate($email, $password);

Logic behind above function is,

 $email = "techbandhus@gmail.com";
 $password = "123456";

 //Load a customer by email address
 $customer = Mage::getModel('customer/customer')
 ->setWebsiteId(Mage::app()->getStore()->getWebsiteId())
 ->loadByEmail($email);

 // if loaded! get stored password from database
 $hash = $customer->getData("password_hash");

 // Get last two digits separate by :";
 $hashArr = explode(':', $hash);

 public function validateHash($password, $hash)
 {
     $hashArr = explode(':', $hash);
     switch (count($hashArr)) {
         case 1:
             return $this->hash($password) === $hash;
         case 2:
             return $this->hash($hashArr[1] . $password) === $hashArr[0];
     }
     Mage::throwException('Invalid hash.');
  }

So, it simply means that even if you have not added salt key and only MD5 text as password, login will work.

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') ?>